JavaScript Interview Question #71

What is the difference between DOMContentLoaded and load?

DOM, Events & Event Loop Fundamentals Mid-Level Intermediate

Quick Interview Answer

DOMContentLoaded fires after the HTML document has been parsed and the DOM is ready, without waiting for every image and other external resource to finish loading. The window load event fires after the page and its dependent resources have finished loading.

Detailed Explanation

DOMContentLoaded fires after the HTML document has been parsed and the DOM is ready, without waiting for every image and other external resource to finish loading. The window load event fires after the page and its dependent resources have finished loading.

DOMContentLoaded is often sufficient for DOM initialization when scripts cannot simply be placed or loaded in a way that already guarantees the required elements are available.

Code Example

document.addEventListener("DOMContentLoaded", () => {
    console.log("DOM is ready");
});

window.addEventListener("load", () => {
    console.log("Page resources are loaded");
});