Working with onload events in vanilla JS

All the different ways of dealing with onload events in the DOM

By: Ajdin Imsirovic 28 November 2020

There are a few ways that we can deal with the onload event in vanilla JS. For example, we might want to wait until everything has loaded, or we could be interested in listening to the event that triggers after only the HTML of the page has finished loading.

Computer screen with code

Listening for the DOMContentLoaded event

To check if the HTML has fully loaded, we listen for the DOMContentLoaded event. This doesn’t include the loading of outside styles and images.

document.addEventListener('DOMContentLoaded', function(event) {
  // code that will run when the DOMContentLoaded event triggers  
};

Listening for the load event

The load event is triggered in the DOM after all the HTML, CSS, JS and images have loaded on the page. We can listen for that event using the following code:

window.addEventListener('load', function(event) {
  // code that will run when the load event triggers    
});

Using the onload property on the global object

We don’t have to use the addEventListener() method; instead we can access the onload property directly on the global object:

window.onload = function(event) {
  // code that will run when the onload property is true
};

Two ways to check the ready state change

We can also check the ready state change to see if all the HTML, styles, and images have loaded. This can be done in two ways.

In both approaches, we check if the document.readyState is set to complete. The two other possible values for document.readyState are: interactive and loading.

The loading value is true while the document is being loaded.

The interactive value is true after the document is finished loading, but the external styles, iframes, and images have not finished loading. In other words, interactive is true if the DOMContentLoaded event has just triggered, but the load event has not yet triggered.

The complete value is when everything has loaded; the next thing that happens is the firing of the 1oad event.

The first approach:

document.onreadystatechange = function(event) {
    if (document.readyState === "complete") {
        // code that runs when the readyState is set to complete
    }
};

The second approach:

document.addEventListener('readystatechange', function(event) {
    if (document.readyState === "complete") {
        // code that runs when the readyState is set to complete
    }
});

Feel free to check out my work here: