The process of rendering a page

1. Process HTML tags and build DOM trees. 2. Process CSS tags and build CSSOM trees. 3. Merge DOM and CSSOM into a render tree. 4, according to the rendering tree layout, calculate the geometric information of each node. 5. Draw each node to the screen.

Note: 1. These five steps are not necessarily done all at once, and are repeated when the DOM or CSSOM is modified by CSS or Javascript. 2. The key render path requires that we have both DOM and CSSOM to build the render tree.

Block rendering

CSS block rendering

1. Because CSS is considered a resource that blocks rendering, browsers do not render any processed content until CSSOM is built. 2. When CSSOM is built, JavaScript execution is paused until CSSOM is ready. CSS does not block the parsing of HTML, but it does block the building of the rendering tree, so we need to download it to the client as soon as possible to reduce the first rendering time. That is, we try to put the tags that are introduced into the CSS inside the head tag.

JS block rendering

JS blocks DOM parsing and rendering. JavaScript can read and modify BOTH DOM properties and CSSOM properties. Therefore, the position of the script tag is important, and in practice we usually place the script tag at the bottom of the body.

Change the blocking mode: defer and async

Because of the blocking conditions described above, we need to change them, including defer and Async

Method of use

Add defer and async to the script tag:

<script src="main1.js" defer></script>
<script src="main2.js" async></script>
Copy the code

defer

Defer represents deferred execution of the imported JavaScript. Documents are parsed sequentially, the download begins when a JavaScript script is encountered, and the HTML continues to be parsed in parallel. If the script is downloaded, it will not start executing until the document has been parsed.

async

Async means to introduce Javascript asynchronously. As before defer, the document was parsed in sequence. The download started when the JavaScript script was encountered and the HTML continued to be parsed, but the difference was that after the script was downloaded, if the document was not parsed, the parsing would be stopped and the downloaded script would be executed first.

Note: defer and async are not valid for inline-script

<script async>
  console.log("1");
</script>
<script defer>
  console.log("2");
</script>
<script>
  console.log("3");
</script>
Copy the code

This is the same as not adding, the console is still typing 123 in order.

conclusion

  • The browser rendering process follows the previous five steps and may be repeated.

  • CSS does not block DOM parsing, but it does block DOM rendering. JS blocks both DOM parsing and DOM rendering.

  • Methods to optimize blocking rendering are async and defer.

If you find my articles useful, please like them and follow them. Also, please visit my personal blog github.com/BokFang