“This is my fourth day of participating in the First Challenge 2022. For more details: First Challenge 2022.”
background
I wrote an article about the different results of different DOM operations. The article just briefly introduced the time when HTML and external resources execute JS scripts. In fact, this can be further expanded, such as the relationship between JS and DOMContentLoaded. That’s what this article will cover
HTML and the DOM
When we request a web page, the requested HTML is first followed by the download of external resources and JAVASCRIPT scripts, so the DOM is built first in order
The DOMContentLoaded event is triggered when the DOM tree is built. That’s because you’ve probably already visited the page twice, the page is already cached, and the difference between Load and DOMContentLoaded is that load takes the time to load an external resource, For example, images, CSS style sheets, if they are cached, then the time difference between the two events will not be too big
External resources do not affect the results of the DOMContentLoaded event because they are downloaded asynchronously by a dedicated download thread, but scripts do (JavaScript,JS), see how render Tree is generated
Synchronous JS
HTML parsing, encounter synchronous JS, have to let it execute first, how to see out? Here’s a little example
<! DOCTYPEhtml>
<html>
<head>.</head>
<body>
<script>
document.addEventListener("DOMContentLoaded".() = > {
console.log("Text appears");
});
for (let i = 0; i < 1000000000; i++) {}
console.log("end");
</script>
<p>When on earth will I be resolved?</p>
</body>
</html>
Copy the code
The
element has a delay before it can manifest itself. Some family members may ask, “This is not true. You put
Note that this synchronous JS actually has two parts, download + execute, because the above is in the HTML code, so there is no download, you can open the server in the background, set the delay return, such as 3S, will also cause white screen, 3s and then render the CONTENT of the DOM. And this JS download is before DOMContentLoaded
<! DOCTYPEhtml>
<html>
<head>.<script src="http://localhost:8000/temp.js"></script>
</head>
<body>
<p>When on earth will I be resolved?</p>
</body>
</html>
Copy the code
Asynchronous JS
Asynchronous JS has the following classes
- An ajax request
- The worker of JS
The reason for the first two is that the process of sending a request to return will not block the PARSING of HTML, while for the worker, it is a background task, equivalent to another thread, which will not block our GUI rendering thread
conclusion
If
<script defer></script>
Copy the code
Understanding the relationship between HTML parsing and JS can actually help us optimize the white screen time and correct DOM manipulation
The resources
How browsers work
Browser Rendering process