How to usethe window.onload event in Javascript

The window.onload event is triggered when the entire page, including all assets such as images and scripts, has finished loading. You can use this event to run your JavaScript code after the page has loaded completely. 

Syntax:

window.onload = function() {
...
};

Example: This example illustrates the use of the window.onload event to make the JS code run after the page load.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>
        Using the window.onload event
    </title>
</head>
 
<body>
    <h1 style="color:green">
        w3wiki
    </h1>
    <h1>
        Using the window.onload event
    </h1>
    <p id="message"></p>
    <button onclick="location.reload()">
        Refresh Page
    </button>
 
    <script>
        window.onload = function () {
            setTimeout(function () {
                document.getElementById('message').innerHTML =
                    'The page has finished loading! After 5 second';
            }, 5000); // Delay of 5 seconds
        };
    </script>
</body>
 
</html>


Output:

How to Execute After Page Load in JavaScript ?

JavaScript is often used to add dynamic functionality to web pages, but it can be frustrating when the code runs before the page has finished loading. This can cause errors or unexpected behavior. Fortunately, there are several approaches you can take to ensure that your JavaScript code runs after the page has loaded.

To accomplish this task, the following approaches will be used:

Table of Content

  • Using the window.onload event
  • Using the DOMContentLoaded event

Similar Reads

Approach 1: Using the window.onload event

The window.onload event is triggered when the entire page, including all assets such as images and scripts, has finished loading. You can use this event to run your JavaScript code after the page has loaded completely....

Approach 2: Using the DOMContentLoaded event

...