Difference Between Domcontentloaded and Load Events

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

Difference between load vs DOMContentLoaded

  • DOMContentLoaded - the whole document (HTML) has been loaded.
  • load - the whole document and its resources (e.g. images, iframes, scripts) have been loaded.

Is DOMContentLoaded and document.onload events are same?

Could be useful for someone

source : Difference between DOMContentLoaded and load events

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: http://learn.jquery.com/using-jquery-core/document-ready/

How do you determine the firing order of load and DOMContentLoaded events?

window/body onload fires after all the images are loaded.

From MDN window.onload

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, scripts, links and sub-frames have finished loading.

So window load should come after the image load is fired.

And order of window/body events being triggeed depends on when you register the event listeners

<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener("DOMContentLoaded", function() {
console.log("Head - DOMContentLoaded");
});
document.addEventListener("load", function() {
console.log("head - document load");
});
window.addEventListener("load", function() {
console.log("head - window load");
});
</script>
</head>
<body onload="console.log('BODY ONLOAD')">
<h1>Hello World!</h1>
<img onload="console.log('IMG ONLOAD')" src="https://developer.cdn.mozilla.net/media/redesign/img/logo_sprite.svg?2014-01" alt="Smiley face" width="42" height="42" />

<script>
document.addEventListener("DOMContentLoaded", function() {
console.log("END - DOMContentLoaded");
});
document.addEventListener("load", function() {
console.log("END - document load");
});
window.addEventListener("load", function() {
console.log("END - window load");
});
</script>
</body>
</html>

would result in

  • "Head - DOMContentLoaded"
  • "END - DOMContentLoaded"
  • "IMG ONLOAD"
  • "head - window load"
  • "BODY ONLOAD"
  • "END - window load"

JSBin

And not all browsers support document.load.



Related Topics



Leave a reply



Submit