Ads by ProfitSence

window.onload vs document.onload

Last Updated on Wednesday 5th Oct 2022

window onload vs document onload

The window.onload must wait until all the elements in the page are loaded before it can be executed. All elements refer to the page structure, content and associated files.

In some browsers it now takes over the role of document.onload and fires when the DOM is ready as well.

The document.onload fires when the DOM tree (built from the markup code within the document) is completed.When the DOM is ready which can be prior to images and other external content is loaded.

					window.onload = function() {
  console.log("Finally I'm loaded");


window onload

					  document.addEventListener("DOMContentLoaded", function(event) {
        - Code to execute when only the HTML document is loaded.
        - This doesn't wait for stylesheets, 
          images, and subframes to finish loading.


In JavaScript, the order of document loading from top to bottom, execute while parsing.





$document load

					$(document).ready(function () {




Ways to Execute JavaScript after page load

Execute JavaScript after page load in many different ways.

window.onload js


					window.onload = function ...


javascript document.onload


					document.onload = function ...


loading document

body onload

					<body onload="script();">

  • document.onload JS that is executed after the structure and style are loaded.
  • window.onload Not only must the structure and styles be loaded, but also all the styles, pictures, and resource files will be executed. The Window.onload event will only be triggered when they are completely loaded.


Which event do we hook into when we want to know the DOM has loaded, window.onload or document.onload?

document.onload is fired when the DOM is loaded, which may be before the images/css is loaded. window.onload is invoked only when the entire page is loaded along with all its contents.