December 12, 2013

There is not a lot of differences between window's onload and body onload events except that window's onload event fires at start whereas body's onload event fires once all content is downloaded. So, in case, we need to find an element and update style or content, etc to it, then, body onload is the way to go. Whereas if it does not matter - then we can use either window's onload or body onload event. Below is an example html source code to check when each of the events is fired.

HTML Code Snippet
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4.     <title></title>
  5.     <script>
  6.         function bodyLoad() {
  7.             alert("alert from body onload");
  8.             alert("content from d1: " + document.getElementById("d1").innerText);
  9.         }
  10.  
  11.         function winLoad() {
  12.             alert("alert from window.onload");
  13.             if (document.getElementById("d1") != null) {
  14.                 alert("content from d1: " + document.getElementById("d1").innerText);
  15.             }
  16.             else {
  17.                 alert("failed to find d1");
  18.             }
  19.         }
  20.  
  21.         window.onload = winLoad();
  22.     </script>
  23. </head>
  24. <body onload="bodyLoad()">
  25.     <div id="d1">
  26.         html body
  27.     </div>
  28. </body>
  29. </html>

0 comments:

Reference: Shahed Kazi at AspNetify.com