JavaScript

window.onload vs document.onload in JavaScript

In JavaScript, “window.onload” and “document.onload” are two events often used to ensure that the page is fully loaded before running any code. The document.onload event takes place before the window.onload event when the entire HTML document has loaded, whereas the window.onload event occurs afterward when everything on the page has loaded, including illustrations.

This blog will demonstrate the difference between the window.onload and document.onload in JavaScript.

window.onload vs document.onload in JavaScript

The “window.onload” event is fired when the entire page (including its resources) has finished loading. This means that you can use this event to ensure the page is fully loaded before running any code that relies on the page’s content.

The “document.onload” event is similar to the window.onload, but it only fires when the document’s DOM (the structure of the page’s content) has finished loading. This signifies that you can use this event to ensure that the page’s content is fully loaded and ready to be manipulated before running any code.

What is the Best Approach to Follow?

In general, it is a good idea to use a document.onload instead of the window.onload if you only need to ensure that the page’s content is fully loaded before running your code. This is because document.onload will fire faster than a window.onload, which can improve the performance of your code. However, if you need to ensure that the page’s resources (such as images and stylesheets) are fully loaded before running your code, then you should use the window.onload instead.

How to Use window.onload vs document.onload in JavaScript?

In the given example, we will see how these events identify the document load and window load before running any code.

Call the “document.onload” event that informs you the document is loaded using an alert() message:

document.onload = alert("document_onload");

Call the “window.onload” event and assign the resultant message of an alert() method to it:

window.onload = alert("window_onload");

As you can see, when the page is refreshed, the first document is loaded, and then the window onload method is invoked when the entire page has finished loading:

That’s all about the window.onload and document.onload events in JavaScript.

Conclusion

The “window.onload” and “document.onload” are two JavaScript events to make sure the complete page loads before executing any code. The document.onload will fire faster than window.onload, which can improve the performance of the code. This blog demonstrated the difference between window.onload and document.onload in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.