onload
The window’s load event
For the window
object, the load
event is fired when the whole webpage (HTML) has loaded fully, including all dependent resources, including JavaScript files, CSS files, and images.
To handle the load
event, you register an event listener using the addEventListener()
method:
Or use the onload
property of the window
object:
If you maintain a legacy system, you may find that the load
event handler is registered in of the body element of the HTML document, like this:
It’s a good practice to use the addEventListener()
method to assign the onload
event handler whenever possible.
The image’s load event
The load
event also fires on images. To handle the load
event on images, you use the addEventListener()
method of the image elements.
The following example uses the load
event handler to determine if an image, which exists in the DOM tree, has been completely loaded:
You can assign an onload
event handler directly using the onload
attribute of the <img>
element, like this:
If you create an image element dynamically, you can assign an onload
event handler before setting the src
property as follows:
How it works:
First, create an image element after the document has been fully loaded by placing the code inside the event handler of the window’s load event.
Second, assign the
onload
event handler to the image.Third, add the image to the document.
Finally, assign an image URL to the
src
attribute. The image will be downloaded to the element as soon as thesrc
property is set.
The script’s load event
The <script>
element also supports the load
event slightly different from the standard ways. The script’s load
event allows you to check if a JavaScript file has been completely loaded.
Unlike images, the web browser starts downloading JavaScript files only after the src
property has been assigned and the <script>
element has been added to the document.
The following code loads the app.js
file after the page has been completely loaded. It assigns an onload
event handler to check if the app.js
has been fully loaded.
Summary
The
load
event occurs when the document has been completely loaded, including dependent resources like JavaScript files, CSS files, and images.The
<img>
and<script>
elements also support theload
event.Use the
addEventListener()
method to register anonload
event handler.
Last updated