What is the difference between window.onload and document.onload in Javascript?


document.onload

It gets fired prior to loading of images and other external content. document.onload event is fired before the window.onload.

window.onload

It gets fired when the complete page loads, which includes images, scripts, css, etc.

Example

Here’a an example to understand onload.

Live Demo

<html>
   <head>
      <title>JavaScript Animation</title>
      <script>
         <!--
            var imgObj = null;
         
            function init() {
               imgObj = document.getElementById('myImage');
               imgObj.style.position= 'relative';
               imgObj.style.left = '0px';
            }

            function moveRight() {
               imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
            }
            window.onload =init;
         //-->
      </script>
   </head>

   <body>
      <form>
         <img id="myImage" src="/images/html.gif" />
         <p>Click button below to move the image to right</p>
         <input type="button" value="Click Me" onclick="moveRight();" />
      </form>
   </body>
</html>

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 15-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements