Waiting for the document to load

Download dom eBook

Example

One of the most commonly used events is waiting for the document to have loaded, including both script files and images. The load event on document is used for this.

document.addEventListener('load', function() {
   console.log("Everything has now loaded!");
});

Sometimes you try to access a DOM object before it is loaded, causing null pointers. These are really tough to debug. To avoid this use document's DOMContentLoaded event instead. DOMContentLoaded ensures that the HTML content has been loaded and initialized without waiting for other external resources.

document.addEventListener('DOMContentLoaded', function() {
   console.log("The document contents are now available!");
});

Stats

Contributors: 5
2016-08-10
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook