Execute a script when the element is finished loading in HTML?


In this article we are going to learn about execute a script when the element is finished loading in HTML.

When an object is loaded, the onload event takes place. Onload is most frequently used in the <body> element to run a script after a web page has loaded all of its content completely. This can be utilised for a number of things, such as checking for cookies or setting the appropriate version of the page based on the user's browser.

Let’s dive into the article to understand more about executing a script when the element is finished loading in HTML.

Using Onload Method

After the element has finished loading, the onload event takes place. To execute a script after the webpage has fully loaded, use this together with the body element.

Syntax

Following is the syntax for onload method.

<body onload="functionToBeExecuted">

Example

In the following example we are using onload method.

<!DOCTYPE html>
<html>
<body onload="loadFunction()">
   <h1>Welcome To TutorialsPoint</h1>
   <script>
      function loadFunction() {
         alert("Loaded Successfully");
      }
   </script>
</body>
</html>

When the script gets executed, the event gets triggered and displays an alert "loaded successfully" on the webpage.

If a user clicks on "OK", the page gets loaded successfully and displays the text "welcome to tutorialspoint".

Using window.onload Method

The window element's onload property is used to execute a script once the webpage has fully loaded. Once the webpage has loaded, the function is activated by the onload property.

Syntax

Following is the syntax for window.onload method

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

Example

Consider the following example we are using window.onload method.

<!DOCTYPE html>
<html>
<body>
   <h1>The Best E-Way Learning.</h1>
   <script>
      function loadFunction() {
         alert("Window Loaded Successfully");
      }
      window.onload = loadFunction();
   </script>
</body>
</html>

On running the above script, the output window pops up, displaying the alert "windows loaded successfully" when the event gets triggered on the webpage.

When the users click OK, the window gets loaded successfully and displays the text "the best e-way learning" on the webpage.

Updated on: 22-Nov-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements