Detailed Explanation of JavaScript DOMContentLoaded Event Case

  • 2021-11-14 04:53:16
  • OfStack

DOMContentLoaded event

Literally, it will trigger after dom is loaded.

It is very similar to the window. onload event, but with one definite difference:

The DOMContentLoaded event is triggered after the document is fully loaded and parsed; window. onload event not only the document is completely loaded and parsed, but also related resources are loaded, such as pictures and CSS files;

The next question is when dom is loaded, which starts with browser rendering. The process of browser displaying web pages can be described as follows:

1. Request to get html document, according to the document request more img, css and other resource files;

2. Parse the document to get two things, dom tree and cssom tree;

3. Generating render tree according to the above two tree;

4. Layout according to render tree and draw related elements in it.

Take webkit as an example, its rendering process is as follows:

DOMContentLoaded event trigger timing:

After DOM and before RENDERtree.

JavaScript loading and execution will delay the firing of DOMContentLoaded events.

JavaScript waits for CSS rendering to complete before loading and executing, because the browser cannot determine whether JavaScript requires DOM element information.

To ensure that JavaScript gets the latest information, CSS is loaded and rendered first.

Reference documentation:

Related articles: