Difference between DOMContentLoaded and load events
Asked Answered
A

8

372

What is the difference between DOMContentLoaded and load events?

Architectural answered 10/3, 2010 at 5:32 Comment(1)
A good article -- Page lifecycle: DOMContentLoaded, load, beforeunload, unload.Acropetal
S
269

From the Mozilla Developer Center:

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

Supposed answered 10/3, 2010 at 5:36 Comment(7)
Fyi, the same MDN link [now] also says: "Note: Stylesheet loads block script execution, so if you have a <script> after a <link rel="stylesheet" ...>, the page will not finish parsing - and DOMContentLoaded will not fire - until the stylesheet is loaded."Trevethick
@Trevethick This page gives the reason. html5rocks.com/en/tutorials/internals/howbrowserswork I would recommend watching the video in the page though.Saw
@Saw nice tutorial although that video link is now obsoleteSunup
So the render tree is built after DOMContentLoaded is fired. But DOMContentLoaded doesn't wait for images/sub-resources/subframes to finish loading according to developer.mozilla.org/en-US/docs/Web/API/Window/…. Do you know if these images/subframes/sub resources are called by the Render Tree after it was built, or were they already called by the DOM tree while the render tree was still being built? In other words, does the render tree triggers a bunch of connections to download these images/subframes/subresources or their downloads were already in progress before?Gotten
The question was the DIFFERENCE between A and B, while the answer gives a definition of A. Hm...Mercurochrome
@Mercurochrome ah, but the definition of A includes what B does at the end of it 😉Supposed
Well, that makes another event in the 'loading collection' lolBrit
E
114

The DOMContentLoaded event will fire as soon as the DOM hierarchy has been fully constructed, the load event will do it when all the images and sub-frames have finished loading.

DOMContentLoaded will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange event.

Edisonedit answered 10/3, 2010 at 5:41 Comment(2)
Which event are you referring to when you say "This event"?Evade
"This event" = DOMContentLoaded. It does not work in IE8. If you need to support it use the workaround which CMS links toPlasmasol
S
63

See the difference yourself:

DEMO

From Microsoft IE

The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images. DOMContentLoaded is a great event to use to hookup UI functionality to complex web pages.

From Mozilla Developer Network

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

Soleure answered 6/3, 2014 at 6:19 Comment(6)
Does DOMContentLoaded guarantee that all the scripts (including defer/async) have been loaded? Nothing is said here about scripts: developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoadedHydrogeology
@Sergey Nope. async resources - i.e <script async src=app.js/> - are loaded independently of the rest of page hence DOMContentLoaded would may get triggered before the resource is fetched from serverSoleure
@MehradSadegh I think you are wrong! From MDN documentation: Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating. You can take a look at this SO question, that confirms it: #42951074Sideling
@Jatimir I think defer and async attributes have different behaviour.Soleure
@MehradSadegh You are right, I'm sorry, for some reason I thought you're referring to defer. My bad :)Sideling
@Jatimir Glad you posted anyway, because your contribution was exactely, what I was looking for! Thank you!Flaxen
N
32

DOMContentLoaded==window.onDomReady()

Load==window.onLoad()

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $(document).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $(window).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

See: Using JQuery Core's document-ready documentation.

Noguchi answered 16/1, 2014 at 7:9 Comment(3)
The question is not about jQuery.Veery
@user34660 Not it is, but helpful to understand.Noguchi
there is no such thing as window.onDomReady()Unstrap
I
24

For a full understanding I recommend to read the following articles:

  1. What is DOM and CSSOM: https://developers.google.com/web/fundamentals/performance/critical-rendering-path/constructing-the-object-model
  2. What is the render tree: https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-tree-construction
  3. How is everything related to DOMContentLoaded, load and first print: https://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp

In Short:

The DOMContentLoaded event is fired when the DOM is created (see link 1 for more what the DOM is) and the load event is fired when the DOM, CSSOM and all other resources are loaded. If you don't have Javascript, then the order that your webpage is loaded may look like this: enter image description here

Or in the words of an inspection window, the DOMContentLoaded event will be fired much earlier then the load event (blue line represents DOMContentLoaded, red line represents load event): enter image description here

However, if you use Javascript (that is not async or defer) then the DOM creation will wait for the JS to load. Since JS also modifies CSS, JS will wait for the CSSOM to load.

Since this is the most common situation, the creation of the DOMContentLoaded event actually has to wait in most scenarios for the style-sheets to be loaded as well.

The loading chain look like this then:

enter image description here

So the main difference between DOMContentLoaded and load is, in this situation, only the loading time of the image, which can be downloaded in parallel to your style-sheets and JS.

enter image description here

Note that this doesn't happen if you use async or defer for your JS:

enter image description here

Irtysh answered 18/5, 2021 at 7:30 Comment(0)
D
18
  • domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.

  • loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.

source

Diazotize answered 19/6, 2014 at 18:34 Comment(1)
If i've any script tags with url to JS, would they load before domContentLoaded or after?Rapallo
O
2

Here's some code that works for us. We found MSIE to be hit and miss with DomContentLoaded, there appears to be some delay when no additional resources are cached (up to 300ms based on our console logging), and it triggers too fast when they are cached. So we resorted to a fallback for MISE. You also want to trigger the doStuff() function whether DomContentLoaded triggers before or after your external JS files.

// detect MSIE 9,10,11, but not Edge
ua=navigator.userAgent.toLowerCase();isIE=/msie/.test(ua);

function doStuff(){
    //
}
if(isIE){
    // play it safe, very few users, exec ur JS when all resources are loaded
    window.onload=function(){doStuff();}
} else {
    // add event listener to trigger your function when DOMContentLoaded
    if(document.readyState==='loading'){
        document.addEventListener('DOMContentLoaded',doStuff);
    } else {
        // DOMContentLoaded already loaded, so better trigger your function
        doStuff();
    }
}
Origen answered 7/6, 2020 at 3:16 Comment(0)
I
1

The answer with the highest number of approvers is wrong, at least in the higher version of Chrome 80+.

1、DOMContentLoaded does not fire until the CSS and JavaScript are executed and the DOM is parsed (the document has been loaded)

2、The window.onload event, which does not fire until all network resources, such as CSS and JavaScript, have been loaded, and the DOM has been parsed (the document has been loaded)


Based on Chrome 80+ test results:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DOMContentLoaded , load</title>
  
  <link href="http://localhost/public/css?sleep=5000" rel="stylesheet">
  <!-- 5000 milliseconds after the URL request the server begins to respond -->
</head>
<body>
  <img src="http://localhost/public/img?sleep=8000">
  <!-- 8000 milliseconds after the URL request the server starts responding to the resource -->
  
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      console.log('DOMContentLoaded OKOK')
    })

    window.addEventListener('load', () => {
      console.log('window load OK')
    })
  </script>

  <script src="http://localhost/public/js?sleep=2000"></script>
  <!-- 2000 milliseconds after the URL request the server begins to respond -->
</body>
</html>

Test execution results: After the page is running for 5 seconds, console.log('domContentLoaded OKOK'), is carried out

console.log(' Window Load OK') starts running at 8 seconds

Ironsides answered 3/3, 2021 at 9:33 Comment(2)
This is not correct. DOMContentLoaded fires when the HTML document (and nothing else, neither the stylesheets) has been parsed.Jennifer
Request a test before commentingIronsides

© 2022 - 2024 — McMap. All rights reserved.