On load in vanilla JavaScript Vanilla JS

There are five ways to check if a page has loaded in vanilla JavaScript.

The load event is fired when the page has loaded, including resources such as stylesheets and images. This is how to check for the load event in vanilla JavaScript.

window.addEventListener('load', function(event) {
    
});

This is another way to check for the load event in vanilla JavaScript.

window.onload = function(event) {
    
};

If you only care if HTML is loaded, the DOMContentLoaded event fires when the HTML has been loaded without waiting for stylesheets or images. This is how to check for the DOMContentLoaded event in vanilla JavaScript.

document.addEventListener('DOMContentLoaded', function(event) {
    
};

This is how to check if a page has loaded by the ready state of the document in vanilla JavaScript.

document.addEventListener('readystatechange', function(event) {
    if (document.readyState === "complete") {
        
    }
});

This is another way to check if a page has loaded with a ready state change event in vanilla JavaScript.

document.onreadystatechange = function(event) {
    if (document.readyState === "complete") {
        
    }
};

document.readyState can have one of three values: complete, interactive and loading.

Complete means that the document and all sub-resources have finished loading and indicates that the load event is about to fire.

Interactive means that the document has finished loading but sub-resources such as stylesheets, images and frames are still loading. This is similar to the DOMContentLoaded event.

Loading means that the document is still loading.

Learn more about the load event on MDN
Learn more about the DOMContentLoaded event on MDN
Learn more about document.readyState on MDN

Thanks for reading.
Ryan

Published on 22 Mar 2019 (on a previous domain)
Last modified on 3 Jun 2021