We may want to wait for the page to load before executing a JavaScript code.

There are two main events commonly used for this purpose: The DOMContentLoaded event and the window load event.

However, there is one key difference between the two events, which I will cover in this post.

DOMContentLoaded event

The DOMContentLoaded event is triggered as soon as the HTML structure is loaded.

This means that the JavaScript code that listens to this event will be executed after the HTML elements have loaded, but without waiting for other files (such as stylesheets, images, and external scripts) to be loaded.

If no special dependency on another external file is required, this event is usually the appropriate choice (and not the other window load event, as there is no reason to wait for the entire page to be loaded).

The implementation is simple:

document.addEventListener('DOMContentLoaded', () => {
	// The code here will be executed once the HTML structure is fully loaded.
});

Window load event

This event, unlike the DOMContentLoaded event, waits for the whole page to be fully loaded.

This means that the JavaScript code will only be executed after the entire page has loaded, including external files such as stylesheets and images.

The implementation:

window.addEventListener('load', () => {
	// The code here will be executed once the entire page is fully loaded.
});