W3docs

How to Make JavaScript Execute After Page Load

Read this JavaScript tutorial and learn which are the two most used methods of making the script execute as soon as the webpage has completely loaded.

It’s important to be sure that JavaScript doesn’t run before the page load. In this tutorial, you will get the right answer to your question of making the JavaScript run after the page load. Here are the two methods which can help you get the work done correctly.

The onload Method

The onload event occurs after the element has finished loading. This can be used with the body element to run a script after the webpage has fully loaded:

Javascript onload method

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body onload="loadFunction()">
    <h1>Welcome to W3Docs</h1>
    <script>
      function loadFunction() {
        alert("Page is loaded");
      }
    </script>
  </body>
</html>

The window.onload Method

The onload property with the window element is used to run a script after the webpage has completely loaded. The onload property fires the function as soon as the webpage has been loaded:

Javascript window.onload method

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h1>Welcome to W3Docs</h1>
    <script>
      function loadFunction() {
        alert("Window is loaded");
      }
      window.onload = loadFunction;
    </script>
  </body>
</html>
Info

This method is accepted to be unobtrusive and more standard.

The window.onload Property

The onload property is an event handler that processes load events on a Window, XMLHttpRequest, HTML <img> element, etc. The onload property processes load events after the element has finished loading. The window global variable represents the window in which the script is executing, and is exposed to JavaScript code.