View video tutorial

HTML onload Attribute

HTML

The HTML onload attribute is an event handler that triggers a script to execute when an object finishes loading.

Definition and Usage


➔ It is typically used with the <body> element to begin working once a complete web page, including all content such as images, audio files, video files, scripts, and CSS files, is fully loaded.

➔ When used with the <body> tag, onload ensures that JavaScript functions are executed after the page has fully rendered, enabling tasks such as fetching data, initiating interactive elements, or manipulating the Document Object Model (DOM).

Syntax
//In HTML    
 <body onload="myFunction()"> 

// In Javascript object 
object.onload =function() {myHandler()};

// In Javascript object 
object.onload = (event) => { };

// Using EventListener 
object.addEventListener("load", (event) => { });

Example
//In <body>
 <body onload="myFunction()"> 

// In <img> 
<img src="sample.gif" onload="myFunction()" width="150" height="100">

// In <input type="image">
<input type="image" onload="myFunction()" src="sample.gif" alt="Button image">

Applies to

This attribute can be used on the following element.

Attribute Element
onload <body>, <iframe>, <img>, <input>, <link>, <script>, <style>

Example

<!DOCTYPE html>
<html>
<head>
    <title>HTML onload Attribute Example</title>
    <meta charset="utf-8" />
</head>
<body onload="myFunction(event)">
    <h2>HTML onload Attribute Example</h2>
    <p>Once the page is fully loaded, the script will be executed.</p>
    <p id="demo"></p>
    <script>
        function myFunction(e) {
            const timestamp = Date.now(e.timestamp);
            const date = new Date(timestamp);
            let localtime = date.toLocaleString([], {
                hour: "2-digit",
                minute: "2-digit",
                second: "2-digit",
            });
            document.querySelector("#demo").textContent = "Loading time: " + localtime;
            alert("The page is fully loaded at: " + localtime);
        }
    </script>
</body>
</html>
Try it Now »

Click on the "Try it Now" button to see how it works.