onload

The onload event is triggered when an object has finished loading. It is most commonly used within the <body> element to execute a script once a web page has fully loaded.

onload event

The onload event handler executes a script when a page or an element has finished loading. It can be applied to the <body> tag or other elements like images to run JavaScript once the content is fully loaded.

Syntax

In HTML

index.html
<element onchange="myScript">

In JS

script.js
object.onload = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("load", myScript);

Example

::event-onload ::
index.html
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<h1>HTML DOM Events</h1>
<h2>The onload Event</h2>

<script>
function myFunction() {
  alert("Page is loaded");
}
</script>

</body>
</html>

This will trigger an alert once the image has finished loading.

Values

Conclusion

The onload event is a valuable tool for executing scripts once a page or element is fully loaded. It ensures that JavaScript runs only after the necessary content is available, providing a smoother and more reliable user experience.