Open In App

How to Execute After Page Load in JavaScript ?

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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. 

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">
        GeeksforGeeks
    </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:

Approach 2: Using the DOMContentLoaded event

The DOMContentLoaded event is triggered when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. This event can be used to run JavaScript code as soon as the page’s HTML has been loaded.

Syntax:

document.addEventListener('DOMContentLoaded', function() {
...
});

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

HTML




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


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads