Skip to content

js onload Event | Run function on-page is loaded JavaScript

  • by

With the JS onload event, you can Execute JavaScript immediately after a page has been loaded. It works when on when an object has been loaded. onload is most often used within the element to execute a script once a web page is fully loaded.

Syntax

HTML

<element onload="myFunction">

JavaScript

object.onload = function(){myScript};

Examples of JS onload Event

Let’s see the example how to set event on HTML website using scripts.

HTML code– onload in body tag

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
        function codeAddress() {
            alert('Load script');
        }
        
        </script>
    </head>
    <body onload="codeAddress();">
    
    </body>
</html>

Output:

JS on load event

JavaScript code– window.onload = codeAddress;

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('On Load event code');
        }
        window.onload = codeAddress;
        </script>
    </head>
    <body>
    
    </body>
</html>

Output:

Examples of JS onload Event

How to run a function when the page is loaded?

Answer: There are 2 ways to to load script and function on HTML page.

Method 1: Using onload method:

<body onload="functionToBeExecuted">

Method 2: The window object represents the browser window.

window.onload = function exampleFunction() {
 
// Function to be executed
}

Q: Where you can use JavaScript onload?

Answer: The onload event can be used to check the visitor’s browser type, browser version, notification, deal with cookies, etc, and load the proper version of the web page based on the information.

Do comment if you have any doubts and suggestion on this tutorial.

Note: The All JS Examples codes are tested on the Firefox browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

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

Continue reading