CSS Portal

HTML onload Event Attribute

If this site has been useful, we’d love your support! 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 information will show you the current browser support for the HTML onload event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.

This event attribute is supported by all modern browsers.
Desktop
Chrome
Edge
Firefox
Opera
Safari
Tablets & Mobile
Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-

Last updated by CSSPortal on: 14th October 2023

If this site has been useful, we’d love your support! Consider buying us a coffee to keep things going strong!