What is the difference between DOMContentLoaded and load events?
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.
For a full understanding I recommend to read the following articles:
What is DOM and CSSOM: https://developers.google.com/web/fundamentals/performance/critical-rendering-path/constructing-the-object-model
What is the render tree: https://developers.google.com/web/fundamentals/performance/critical-rendering-path/render-tree-construction
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:
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.
Note that this doesn't happen if you use async or defer for your JS:
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
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
Related
I've been reading a lot about jQuery.ready() will slow your page down. My website has a bunch of code running inside jQuery.ready() as many websites do.
</body>
<script>
jQuery(document).ready(function() {
// Do some event binding and initialization.
});
</script>
I place this script at the end of <body> tag but I wrapped the code inside DOM ready just to be safe.
Now I test my page with http://www.webpagetest.org/ and I noticed that the domContentLoaded time is as follows:
domContentLoaded
4.987s - 5.317s (0.330s)
Now I experimented by removing jQuery.ready(function() {}); to be just
</body>
<script>
// Do some event binding and initialization.
</script>
And I test the page again. Here's the result.
domContentLoaded
3.772s - 3.915s (0.143s)
The execution goes down to just 0.1s which is about ~187ms. Am I right to assume that the execution time goes down because the code is not executed inside jQuery.ready and what does this mean in terms of performance gain, e.g perceived performance. Do users feel that the page loads quicker?
isn't domContentLoaded the same event trapped by $.ready? If webpagetest's timer is taking longer when the main script is running at $.ready, that could just indicate that more threads are competing for resources at that time. it makes sense that allowing any setup and initialization that can run before that event to do so will make all of the setup that happens at document ready run smoother...
domContentLoaded in webpagetest is document.ready in jquery
fire your code on onLoad event to improve performance
if("undefined"==typeof(addOnload)){function addOnload(a){if("undefined"!=typeof(window.attachEvent)){return window.attachEvent("onload",a)}else{if(window.addEventListener){return window.addEventListener("load",a,false)}}};}
call your function on onload event
addOnload(fnName);
In JavaScript, when I want to run a script once when the page has loaded, should I use window.onload or just write the script?
For example, if I want to have a pop-up, should I write (directly inside the <script> tag):
alert("hello!");
Or:
window.onload = function() {
alert("hello!");
}
Both appear to run just after the page is loaded. What is the the difference?
The other answers all seem out of date
First off, putting scripts at the top and using window.onload is an anti-pattern. It's left over from IE days at best or mis-understandings of JavaScript and the browser at worst.
You can just move your scripts the the bottom of your html
<html>
<head>
<title>My Page</title>
</head>
<body>
content
<script src="some-external.js"></script>
<script>
some in page code
</script>
</body>
</html>
The only reason people used window.onload is because they mistakenly believed scripts needed to go in the head section. Because things are executed in order if your script was in the head section then the body and your content didn't yet exist by definition of execute in order.
The hacky workaround was to use window.onload to wait for the rest of the page to load. Moving your script to the bottom also solved that issue and now there's no need to use window.onload since your body and content will have already been loaded.
The more modern solution is to use the defer tag on your scripts but to use that your scripts need to all be external.
<head>
<script src="some-external.js" defer></script>
<script src="some-other-external.js" defer></script>
</head>
This has the advantage that the browser will start downloading the scripts immediately and it will execute them in the order specified but it will wait to execute them until after the page has loaded, no need for window.onload or the better but still unneeded window.addEventListener('load', ...
window.onload just runs when the browser gets to it.
window.addEventListener waits for the window to be loaded before running it.
In general you should do the second, but you should attach an event listener to it instead of defining the function. For example:
window.addEventListener('load',
function() {
alert('hello!');
}, false);
Here's the documentation on MDN.
According to it:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
Your first snippet of code will run as soon as browser hit this spot in HTML.
The second snippet will trigger popup when the DOM and all images are fully loaded (see the specs).
Considering the alert() function, it doesn't really matter at which point it will run (it doesn't depend on anything besides window object). But if you want to manipulate the DOM - you should definitely wait for it to properly load.
That depends on if you want it to run when the script element is encountered or if you want it to run when the load event fires (which is after the entire document (including such things as images) has loaded).
Neither is always right.
In general, however, I'd avoid assigning functions directly to onload in favour of using addEventListener (with compatibility libraries if I needed to support older browsers).
The reason for waiting for the DOM to be loaded is so that you can target any elements that load after your script. If you're just creating an alert, it doesn't matter. Let's say, however, you were targeting a div that was in your markup after your script, you would get an error if you don't wait until that piece of the DOM tree to load.
document.ready is a great alternative to window.onload if you're using jQuery.
See here: window.onload vs $(document).ready()
You have three alternatives:
Directly inside the script tag runs it as soon as it is parsed.
Inside document.addEventListener( "DOMContentLoaded", function(){}); will run it once the DOM is ready.
Inside window.onload function(){}) will run as soon as all page resources are loaded.
I was on jsfiddle.net recently and I saw this as a configuration option. This got me to thinking that it might help a problem I'm having as such:
I load multiple images (haven't upgraded to a single sprite yet) so that I can not use my controls until they are all downloaded...the images take most of the download time so that for the first few seconds I can not access my controls.
Currently I'm using one of these two..both work.
window.onload = initialize_page
window.addEventListener('load',initialize_page);
Related
Jquery document ready vs. window.onload
window.onload vs. body.onload vs. document.onready
window.onload vs <body onload=""/>
AFAIK onDomReady() fires once the DOM has loaded. If the page contains external sources, such as images, then it may fire before these have finished loading.
onLoad() fires after the whole page has finished loading, including external sources.
So it's possible for onDomReady() to fire before onLoad() but you'll have to test it on your page.
so often i put jquery document ready functions at the bottom of my html, just to have it run before all the elements of the page are loaded. i'm tired of my functions not working because resources arent finished loading on the page, jquery.ready keeps saying the elements are done loading when they arent! who wants to set a 300ms timeout just so that their functions wait a little after jquery.ready?
Use .ready() to perform actions when the DOM is ready for scripting.
$(document).ready(function(){
});
Use .load() to perform actions when the "page" (resources including files and images) is loaded.
$(window).load(function(){
});
jQuery.ready fires when DOM elements are ready, not when scripts/images/etc finish loading.
Description from the docs on .ready():
Specify a function to execute when the DOM is fully loaded.
As simshaun said, jQuery.ready fires when the DOM is ready - not when things like images are ready. If you want to wait for images to be loaded, you have to use the following code:
$(window).load(
function() {
// do stuff here
}
);
$.ready runs when DOM is loaded not when the page is fully loaded (images etc...)
Perhaps you're looking for
$(window).load(function() {
// stuff
});
From the jQuery API documentation:
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
So, use the load event if you need everything to be finished loading but if you only need the DOM to be ready, use the ready event.
.ready() function runs when the DOM is ready not the binary data is loaded. to ensure that the binary data is loaded you can use .load() function
We have a JQuery $(function() statement as:
<script type="text/javascript">
$(function(){
//Code..
})
</script>
Dumb question - when exactly is this function executed? Is it when the entire HTML page has been downloaded by the client?
What is benefit of using the wrapping your code within $(function() as opposed to just doing:
<script type="text/javascript">
//Code..
</script>
It fires when the document has been parsed and is ready, and is the equivalent of $(document).ready(function () { }).
The obvious benefit is that having your script tag before other elements on the page means that your script can interact with them even though they're not available at parse time. If you run your script before elements have been parsed and the document is not ready, they will not be available for interaction.
It is executed as soon as the DOM is parsed and is invoked in order of appearance if there are multiple appearances. At this point the document is however not displayed, its just parsed.
When the document completes loading. It is the same as writing this:
$(document).ready(function(){});
EDIT: To answer your second question:
If you don't wrap your code in the block above then it would fire as soon as it is encountered instead of after all the controls on the page have loaded. So if a block was at the top of a page and it referred to elements in the page those references would not work as the elements have not loaded yet.
But if you wrap in the block then you know that the page has loaded and all elements are available to now reference.
It fires after the the document has fully loaded, the DOM tree has been initialized, all CSS styles have been applied and all Javascript has been executed. It differs from the load event in that elements (other than CSS/JS) that load their content from other URLs, such as images or flash files, have not necessarily finished loading at this point. This is usually called the "domready" or "domloaded" event, and some modern browsers support it directly (e.g. Firefox has a DomContentLoaded event), and on others it can be simulated with various tricks, like using the defer attribute or placing a script at the very end of the body.
The advantage is that you can reliably interact with the document at this time; for example you can set an event handler on an element with a certain ID and be sure that it already exists in the DOM tree. On the other hand, it can run considerably earlier than the load event, if some external resource is slow to load. If your script is at the end of your HTML code, then there might be little difference in using or not using the domready event, but usually scripts are called from the head tag, and at that point no elements of the body are available yet.