onload Event
Definition and Usage
The onload event occurs after an object is loaded.
onload is most commonly used in the <body> element, to execute scripts after the web page has completely loaded all content (including images, script files, CSS files, etc.).
The onload event can be used to check the visitor's browser type and version, and load the correct version of the web page based on this information.
The onload event can also be used to handle cookies (see more examples below).
Example
Execute JavaScript immediately after page load:
<body onload="myFunction()">
Example 2
Use onload on <img> element. Display a reminder "Image is loaded" immediately after the image is loaded:
<img src="w3javascript.gif" onload="loadImage()" width="100" height="132"> <script> function loadImage() { alert("Image is loaded"); } </script>
Example 3
Use onload event to handle cookies:
<body onload="checkCookies()"> <script> function checkCookies() { var text = ""; if (navigator.cookieEnabled == true) { text = "Cookies are enabled."; } else { text = "Cookies are not enabled."; } document.getElementById("demo").innerHTML = text; } </script>
Syntax
In HTML:
<element onload="myScript">
In JavaScript:
object.onload = function(){myScript};
In JavaScript, use the addEventListener() method:
object.addEventListener("load", myScript);
Note:Internet Explorer 8 or earlier versions do not support addEventListener() method.
Technical details
Bubbling: | Not supported |
---|---|
Cancelable: | Not supported |
Event type: | If generated from the user interface,UiEvent. Otherwise, Event. |
Supported HTML tags: | <body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style> |
DOM Version: | Level 2 Events |
Browser Support
Events | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
onload | Support | Support | Support | Support | Support |