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

In HTML, executing a script when an element finishes loading is accomplished using the onload event. This event triggers when an element has completely loaded, including all its content, images, and external resources.

The onload event is most commonly used with the <body> element to run scripts after a web page has fully loaded. It can also be applied to individual elements like images, iframes, and objects. This functionality is useful for initialization tasks, form validation, cookie checking, or dynamically adjusting content based on the loaded page.

Syntax

Following is the syntax for the onload event attribute −

<element onload="functionName()">

Following is the syntax for the window.onload property in JavaScript −

window.onload = function() {
   // Code to execute
};

Using the onload Attribute

The onload attribute can be added directly to HTML elements to execute JavaScript functions when the element finishes loading. This method is straightforward and works well for simple scenarios.

Example − Body onload Event

Following example demonstrates using the onload attribute with the body element −

<!DOCTYPE html>
<html>
<head>
   <title>Body onload Example</title>
</head>
<body onload="loadFunction()" style="font-family: Arial, sans-serif; padding: 20px;">
   <h1>Welcome To TutorialsPoint</h1>
   <p>This page loaded successfully!</p>
   <script>
      function loadFunction() {
         alert("Page loaded successfully!");
      }
   </script>
</body>
</html>

The output shows an alert message when the page loads, followed by the page content −

Alert: "Page loaded successfully!"
Welcome To TutorialsPoint
This page loaded successfully!

Example − Image onload Event

The onload event can also be applied to images to execute scripts when they finish loading −

<!DOCTYPE html>
<html>
<head>
   <title>Image onload Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Image Loading Example</h2>
   <img src="https://via.placeholder.com/200x150" 
        alt="Placeholder Image" 
        onload="imageLoaded()" 
        style="border: 2px solid #ccc;">
   <p id="status">Loading image...</p>
   <script>
      function imageLoaded() {
         document.getElementById("status").innerHTML = "Image loaded successfully!";
      }
   </script>
</body>
</html>

The status text changes from "Loading image..." to "Image loaded successfully!" once the image loads completely.

Using window.onload Property

The window.onload property provides a JavaScript-based approach to execute scripts when the entire window and all its resources have finished loading. This method is more flexible and allows for more complex initialization logic.

Example − window.onload Function

Following example shows the proper usage of window.onload −

<!DOCTYPE html>
<html>
<head>
   <title>window.onload Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h1>The Best E-Learning Platform</h1>
   <p id="message">Loading...</p>
   <script>
      window.onload = function() {
         document.getElementById("message").innerHTML = "Window loaded successfully!";
         alert("All resources loaded!");
      };
   </script>
</body>
</html>

The output shows the alert message and updates the page content when all resources finish loading −

Alert: "All resources loaded!"
The Best E-Learning Platform
Window loaded successfully!

Example − Multiple Function Execution

Following example demonstrates executing multiple functions using window.onload −

<!DOCTYPE html>
<html>
<head>
   <title>Multiple Functions Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Page Initialization Demo</h2>
   <p id="time"></p>
   <p id="browser"></p>
   <script>
      function displayTime() {
         var now = new Date();
         document.getElementById("time").innerHTML = "Page loaded at: " + now.toLocaleTimeString();
      }
      
      function displayBrowser() {
         document.getElementById("browser").innerHTML = "Browser: " + navigator.userAgent.substring(0, 50) + "...";
      }
      
      window.onload = function() {
         displayTime();
         displayBrowser();
      };
   </script>
</body>
</html>

This example executes multiple initialization functions when the page loads, displaying the current time and browser information.

Using addEventListener Method

The modern approach uses addEventListener to handle the load event. This method allows multiple event listeners and provides better control over event handling.

Example

<!DOCTYPE html>
<html>
<head>
   <title>addEventListener Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Modern Load Event Handling</h2>
   <div id="content">Content will be updated after loading...</div>
   <script>
      window.addEventListener('load', function() {
         document.getElementById('content').innerHTML = 'Page loaded using addEventListener!';
      });
   </script>
</body>
</html>

The output shows the updated content after the page loads −

Modern Load Event Handling
Page loaded using addEventListener!

Comparison of Load Event Methods

Method Usage Advantages Disadvantages
onload attribute <body onload="func()"> Simple, inline Mixes HTML and JavaScript
window.onload window.onload = function() {} Separates JS from HTML Only one function can be assigned
addEventListener window.addEventListener('load', func) Multiple listeners, modern standard Not supported in very old browsers

Conclusion

The onload event in HTML provides several ways to execute scripts when elements finish loading. Use the onload attribute for simple cases, window.onload for single function execution, and addEventListener for modern, flexible event handling. Choose the method that best fits your project's requirements and browser compatibility needs.

Updated on: 2026-03-16T21:38:53+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements