JavaScript·100 questions

[ITEM 5] QUESTION: Что такое DOMContentLoaded и load?

Answer

The DOMContentLoaded and load events play a key role in the web page loading lifecycle, and understanding the difference between them is critically important for a frontend developer. The DOMContentLoaded event fires on the document object when HTML is fully loaded and parsed, and the DOM tree is completely built. At the same time, the browser does not wait for stylesheets, images, and subframes to load. This makes DOMContentLoaded the ideal moment to initialize interactive interface elements, attach event handlers, and execute basic script logic that does not need image dimensions.

The load event, in turn, fires on the window object slightly later, when not only the HTML and DOM tree are fully loaded, but also all associated resources: stylesheets, scripts, images, and third-party frames. Since loading heavy graphics can take a noticeable amount of time, load occurs significantly later than DOMContentLoaded.

In practice, DOMContentLoaded fires much faster, which helps improve the user-perceived loading speed of the site. To ensure scripts execute on time and do not block page rendering, the defer attribute is often used for the script tag, which instructs the browser to load the script asynchronously in the background and execute it immediately after DOMContentLoaded completes.

To check the current document loading state at any given time, you can use the document.readyState property. It takes three possible values: loading, when the document is still loading; interactive, when the document has been fully read and parsed (which corresponds to the moment before the DOMContentLoaded event); and complete, when all resources are fully loaded (which corresponds to the moment before the load event). This property is convenient to use in universal functions that need to execute regardless of whether the document managed to load before the script was connected.

Was this answer helpful?

More questions in this topic

Related questions from other topics