简体   繁体   中英

Difference between DOMContentLoaded and load events

DOMContentLoadedload事件有什么区别?

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).

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.

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).

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 .

  • 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

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 everthing 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: 在此处输入图片说明

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): 在此处输入图片说明

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:

在此处输入图片说明

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.

在此处输入图片说明

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

在此处输入图片说明

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();
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM