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.
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:
Call the “window.onload” event and assign the resultant message of an alert() method to it:
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: