How to Make JavaScript Execute After Page Load

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 thoroughly loaded:

<!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 thoroughly loaded. The onload property fires the function as soon as the webpage has been loaded:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <h1>Welcome to W3Docs</h1>
    <script>
      function loadFunction() {
        alert("Window is loaded");
      }
      window.onload = loadFunction();
    </script>
  </body>
</html>
This method is accepted to be unobtrusive and more standard.

The Window.onload Function

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.