In HTML, the onload attribute fires when an object has been loaded. The purpose of this attribute is to execute a script when the associated element loads.
In HTML, the onload attribute is generally used with the <body> element to execute a script once the content (including CSS files, images, scripts, etc.) of the webpage is completely loaded. It is not necessary to use it only with <body> tag, as it can be used with other HTML elements.
The difference between the document.onload and window.onload is: document.onload triggers before the loading of images and other external content. It is fired before the window.onload. While the window.onload triggers when the entire page loads, including CSS files, script files, images, etc.
Let's understand this event by using some examples.
In this example, there is a div element with a height of 200px and a width of 200px. Here, we are using the window.onload() to change the background color, width, and height of the div element after loading the web page.
The background color is set to 'red', and width and height are set to 300px each.Test it Now
After the execution of the code and loading of the page, the output will be -
After the successful execution of the above code, the output will be -
After the execution of the above code, the output will be -