Skip to content

Execute JavaScript after page load | onload, document.onload & window.onload

If you are using an <script> inside <head> then use the onload attribute inside the <body> tag to Execute JavaScript after page load. It will run the function as soon as the webpage has been loaded.

It’s not the only way to call the JavaScript function after the page load complete. You can use document.onload or window.onload JavaScript.

Execute JavaScript after page load Example code

These solutions will works for JavaScript run function after page is loaded in HTML webpage:-

1. Example: onload

The onload event occurs when an object has been loaded.

<!DOCTYPE html> 
<html> 
  
  <head>
      <script type="text/javascript">
          function myFun(){
            alert("Load function...")
          }
      </script>
  </head>
  
<body onload="myFun()"> 
    <b> 
        How to run a function when the 
        page is loaded in javascript ? 
    </b> 
      
</body> 
  
</html> 

Output:

Execute JavaScript after page load

2. Example window.onload JavaScript

The window object represents the browser window. The window onload property processes load events after the element has finished loading.

By default, it is fired when the entire page loads, including its content (images, CSS, scripts, etc.).

<!DOCTYPE html> 
<html> 
  
  <head>
       <script> 
        window.onload = function funLoad() { 
            console.log('The Script will load now.'); 
        } 
    </script> 
  </head>
  
</html> 

3. document.onload

It is called when the DOM is ready which can be prior to images and other external content is loaded.

Note: document.onload is not supported by any modern browser (event is never fired)

<!DOCTYPE html> 
<html> 
  
  <head>
       <script> 
        document.onload = function funLoad() { 
            console.log('The Script will load now.'); 
        } 
    </script> 
  </head>
  
</html> 

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “Execute JavaScript after page load | onload, document.onload & window.onload”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading