Cyber Week

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

onload

Reading time 2 min
Published Sep 8, 2017
Updated Oct 10, 2019

JavaScript onload: Main Tips

  • The JavaScript onload event transpires when an object is loaded.
  • onload is most frequently used within the <body> element to perform a script once a website has fully loaded (including script files, images, CSS files, etc.).
  • The onload event shall be used to verify the type of the visitor's browser and version of the browser, and then load an individual web page version based on the information.
  • The onload event can deal with cookies.

onload Event Explained

The JavaScript onload event can be applied when it is necessary to launch a specific function once the page is displayed fully.

Developers often use this event to demonstrate greeting messages and other user-friendly features. It is no surprise that onload JavaScript event can be immediately associated with the <body> element.

Another frequent usage of JavaScript onload is to apply it to automatically check visitors' web browsers and adjust the way websites will be loaded. Furthermore, you can use it to check what cookies does a page use.

The window.onload function is widely supported by popular browsers. It begins as soon as the resource is loaded.

As we already mentioned welcoming messages, we should explain how they can be incorporated into web pages. This example shows how the JavaScript onload event can display an alert box with a specific message and a button:

Example
<body onload="sampleFunction()">
Theory is great, but we recommend digging deeper!

Learn Event Syntax

The onload JavaScript event is not difficult to learn. However, you should pay attention how this event should be written in different languages:

In HTML:

Example
<element onload="sampleScript">

In JavaScript:

Example
object.onload = () => sampleScript();

In JavaScript, with the addEventListener() method:

Example
 object.addEventListener("load", sampleScript);

The addEventListener() method is supported by Internet Explorer 9 and newer versions only.

Code Examples: Best Practice

We understand that students crave practice, not only theory. They do have a point - if you want to master any JavaScript function, property, or event, you need to practice. Therefore, we suggest you play around and learn from all the code examples we provide.

In this example, an <img> element is signed onload. Alert Image is successfully loaded is displayed after an image is loaded:

Example
<img src="https://cdn.bitdegree.org/learn/pom-laptop.png?raw=true" onload="ImageLoad()" width="120" height="120">

Now, in this example, we deal with cookies by using the onload event:

Example
<body onload="checkCookies()">