Home >Web Front-end >JS Tutorial >Window.onload vs Body onload: Which Event Should You Use?
When to Use window.onload vs Body onload Event
The window.onload event and the onload event of the body tag are both used to attach a JavaScript function to be executed when the entire page (including images, styles and frames) is loaded into the browser.
window.onload
The window.onload event is an event handler that is attached to the window object. It is fired when the entire page, including all of its resources (such as images, stylesheets, and scripts), has been loaded.
The onload event of the body tag is an event handler that is attached to the body element. It is fired when the entire page, excluding any external resources, has been loaded.
When to Use Each Event
In general, you should use the window.onload event when you need to execute a function after the entire page, including all of its resources, has been loaded. You should use the onload event of the body tag when you need to execute a function after the page, excluding any external resources, has been loaded.
Example
The following JavaScript code uses the window.onload event to execute a function after the entire page has been loaded:
<code class="js">window.onload = function() { // Perform some action }</code>
The following JavaScript code uses the onload event of the body tag to execute a function after the page, excluding any external resources, has been loaded:
<code class="html"><body onload="myFunction()"> <!-- Page content --> </body></code>
The above is the detailed content of Window.onload vs Body onload: Which Event Should You Use?. For more information, please follow other related articles on the PHP Chinese website!