HTML onload Attribute

HTML onload Attribute: This attribute is defined as it fires when an object has been loaded. It is mostly used within the <body> element to execute a script. It can be used with other elements as well. This attribute is used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information. The onload attribute is a section of the Event Attributes.

HTML onload Attribute

This attribute can be applied to <body>,<iframe>,<img>,<input>,<link>,<script> and <style> elements. This attribute contains single value script and it runs when onload event triggered. This attribute is associated with many HTML elements.

Syntax: <element onload = “script”>



Browser Support

This attribute is supported by the following browsers:

  • Chrome
  • Firefox
  • Safari
  • Opera
  • Internet Explorer

Example: for <body> element

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Welcome!</h1>
</body>
</html>

Output:

Welcome!

Example: for <img> element

<!DOCTYPE html>
<html>
<body>
<img src="https://www.freshersnow.com/wp-content/uploads/2017/11/freshersnow.pngf" onload="loadImage()" width="100" height="132">
<script>
function loadImage() {
  alert("Image is loaded");
}
</script>
</body>
</html>

Output:

HTML img element

Example: for <input> element

<!DOCTYPE html>
<html>
<body>
<input type="image" onload="loadImage()"  src="img_submit.gif" alt="Submit" width="48" height="48">
<script>
function loadImage() {
  alert("Image is loaded");
}
</script>
</body>
</html>

Output:

HTML onload attribute