HTML onload Event Attribute

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

Description

The onload HTML event attribute fires when an object has been loaded. It is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well, such as images and links.

The onload attribute can be used for a variety of purposes, such as:

  • To display a loading animation while the page is loading
  • To initialize JavaScript variables and objects
  • To check the user's browser type and version and load the appropriate content
  • To redirect the user to a different page
  • To display a pop-up message

Here is an example of how to use the onload attribute on the <body> element:

<body onload="myFunction()">
  ...
</body>

The myFunction() function will be executed once the page has completely loaded.

Here is an example of how to use the onload attribute on an image element:

<img src="my-image.png" onload="myFunction()">

The myFunction() function will be executed once the image has been loaded.

Syntax

<element onload="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>onload event</title>
</head>
<body>
<img src="2.png" alt="CSS" onload="LoadInfo()">
<p id="test"> </p>
<script>
function LoadInfo() {
document.getElementById("test").innerHTML = "Image loaded successfully!";
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onload Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 14th October 2023