Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Difference between window.onload and body.onload

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

There is a slight difference between the windows onload and the body onload, but before approaching the differences between them first we required the knowledge of what are those onloads. After, that we will know the usage in different scenarios of those where we will notice the slight differences between them.

onloads: The onloads event is fired when an object is fully loaded, there are two types of onload event one is windows onload and body onload.

  1. Windows onload: This window’s onload event fires at the start.
  2. Body onload: This body onload event fires once all content is downloaded, if we want to find an element and update the style or content, then, body onload is the right choice to use.

Note: If update the style and content do not bother you then it does not matter which onload you are using.

The below example illustrates the differences between windows onload and body onload:

HTML




<!DOCTYPE html>
<html>
   <head>
   </head>
   <body onload="bodyLoad()">
      <div id="B1">
         <h1 style="color: green;">GeeksforGeeks</h1>
           
<p>A Computer Science Portal for Geeks</p>
  
      </div>
      <script>
          
        // Body onload
         function bodyLoad() {
             alert("Alert from body_onload");
             alert("content from d1: "
                   + document.getElementById("d1").innerText);
         }
           
         // Window onload 
         function winLoad() {
             alert("Alert from window_onload");
             if (document.getElementById("B1") != null) {
                 alert("Content from body: "
                       + document.getElementById("B1").innerText);
             }
             else {
                 alert("Failed to find B1");
             }
         }
         window.onload = winLoad();
      </script>
   </body>
</html>


Output:

  • Window onload:

  • Body onload:


My Personal Notes arrow_drop_up
Last Updated : 10 Feb, 2021
Like Article
Save Article
Similar Reads
Related Tutorials