Home > Web Front-end > JS Tutorial > Window.onload vs Body onload: Which Event Should You Use?

Window.onload vs Body onload: Which Event Should You Use?

Susan Sarandon
Release: 2024-11-02 07:23:29
Original
356 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template