Table of contents
1.
Introduction
2.
What is onload in JavaScript?
3.
Syntax of onload in JavaScript
4.
Return Value of Onload in JavaScript
5.
Uses of onload in JavaScript
6.
Examples
6.1.
Example 1
6.1.1.
Code
6.1.2.
Output
6.1.3.
Explanation
6.2.
Example 2
6.2.1.
Code
6.2.2.
Output
6.2.3.
Explanation
6.3.
Example 3
6.3.1.
Code
6.3.2.
Output
6.3.3.
Explanation
7.
Working of Onload in JavaScript
8.
Supported Browser
9.
Frequently Asked Questions
9.1.
Is onload a JavaScript event?
9.2.
Can we use onload to load external scripts?
9.3.
How can onload improve performance?
9.4.
Can we assign multiple functions to the onload event?
9.5.
Can we trigger the onload event manually?
9.6.
Do all browsers support the onload event?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

JavaScript onload

Author Akshat Aggarwal
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JavaScript is a programming language that runs in a browser and makes interactive web pages. An event is something that happens in the system. JavaScript can execute code when some event occurs, and this code is called an event handler. The load event fires when the page loads completely, automatically calling the onload event handler.

Javascript onload

This article will discuss the onload event handler and its uses.

What is onload in JavaScript?

The onload event handler is a function that runs a script after the load event fires. We can use the onload event handler inside. We can assign this event handler to an element, and it will run after all dependent resources of the element completely load.

Now let us look at the syntax for JavaScript onload.

Syntax of onload in JavaScript

In JavaScript, we have two ways to define this event handler. First, we can use the onload property of an element and assign a function to it.

element.onload = functionName;


Second, we can add an event listener for the load event.

element.addEventListener(“load”, functionName);


Lastly, we can use the onload attribute of an event in HTML and assign a function to it.

<element onload=”functionName()”>

Return Value of Onload in JavaScript

The onload in JavaScript doesn't have a return value. It's an event handler that executes a block of code when a specified object, typically a webpage or an image, has finished loading in the browser. Its purpose is to trigger actions or functions after the associated resource has fully loaded, such as performing additional operations on the page or manipulating the loaded content.

Uses of onload in JavaScript

We can use the onload function to:

  1. Execute some code after the page has completely loaded, which we can use to load different webpage versions according to the browser type.
     
  2. Display images after they load entirely.
     
  3. Fetch more data after the page loads.
     
  4. Handle cookies (set or read them) after the page loads.

Examples

Let us illustrate the use of the onload function using some examples.

Example 1

Code

<!DOCTYPE html>
<html>

<head>
    <title>JavaScript onload Example 1</title>
    <script>
        window.onload = () => {
            let img = document.createElement("img");
            img.src = './CodingNinjas.svg';
            document.body.append(img);
        };    
    </script>
</head>

<body>
    <script>
        alert('This alert stops page from loading.');
    </script>
</body>

</html>

OutputOutput example 1

After clicking OK in the alert box, the image loads (as shown below).

Output

Explanation

In this code, we assign an arrow function to the window.onload property. We create a new img element inside the arrow function and set its src attribute to a local image. As the alert function interrupts the page loading, the onload function does not execute until we close the alert box.

Example 2

Code

<!DOCTYPE html>
<html>

<head>
    <title>JavaScript onload Example 2</title>
    <script>
        function loadBackground() {
            document.body.style.backgroundColor = "lightgreen";
        };
        window.addEventListener("load", loadBackground);
    </script>
</head>

<body>
    <script>
        alert('This alert stops page from loading.');
    </script>
</body>

</html>

Output

Output

After clicking OK in the alert box, the background colour changes to light green.

Output

Explanation

In this code, the window.addEventListener method attaches the loadBackground function to the load event of the window object. Thus the loadBackground function executes when the entire page has finished loading and changes the background colour.

Example 3

Code

<!DOCTYPE html>
<html>

<head>
    <title>JavaScript onload Example 3</title>
    <script>
        let imagesLoaded = 0;
        const totalImages = 2;

        function allImagesLoaded() {
            const statusElement = document.getElementById('status');
            statusElement.textContent = 'All images have been loaded!';
        }

        function imageLoaded() {
            imagesLoaded++;
            if (imagesLoaded === totalImages) {
                allImagesLoaded();
            }
        }
    </script>
</head>

<body>
    <img src="CodingNinjas.svg" alt="Image 1" onload="imageLoaded()">
    <img src="CodingNinjas.svg" alt="Image 2" onload="imageLoaded()">
    <p id="status"></p>
</body>

</html>

Output

Output

Explanation

In this code, we are using the onload event to track the number of images that have been loaded and display a message once all the images have loaded.

The p element has an id of "status", which the allImagesLoaded function uses to display a message.

Working of Onload in JavaScript

The onload in JavaScript is a crucial event handler. It is used to execute code when a specified element or resource has fully loaded. This event is commonly used with elements like images, scripts, and web pages. Here's how it works:

  1. Event Binding: We can attach the onload event handler to an HTML element or resource that we want to monitor, such as an image or the window object
     
  2. Loading Process: When the specified element or resource starts loading, the onload event handler is registered to listen for its completion
     
  3. Execution: Once the loading process is complete, the associated onload code is executed. This code can perform various actions, such as manipulating the loaded content or updating the webpage's state

Supported Browser

The onload event is well-supported in all major web browsers. This is supported by Chrome, Firefox, Safari, Edge, and Internet Explorer. This widespread support ensures that web developers can rely on the onload event to create interactive and responsive web applications across different browsers.

However, it's important to handle potential differences in browser behavior or quirks when working with complex applications. Testing and cross-browser compatibility checks are recommended to ensure consistent behavior across various browser environments.

Frequently Asked Questions

Is onload a JavaScript event?

Yes, onload is a JavaScript event. It occurs when an object (typically a webpage or an image) has fully loaded in the browser. It's commonly used to execute JavaScript code after a webpage or its resources have finished loading.

Can we use onload to load external scripts?

Yes, we can use onload to load external scripts.

How can onload improve performance?

Onload can improve performance if the page resources start loading after the page's main content is loaded.

Can we assign multiple functions to the onload event?

We can assign multiple functions to the onload event using the addEventListener method instead of directly assigning a function to the onload property.

Can we trigger the onload event manually?

We can trigger the onload event manually using the dispatchEvent method.

Do all browsers support the onload event?

All modern browsers support the onload event, including Chrome, Firefox, Safari, and Edge. 

Conclusion

This article discussed Javascript onload and its uses. The onload event allows us to ensure that specific actions occur only after the page completely loads, which can improve the user experience.

To learn more about web development, we recommend reading the following articles:

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Happy Coding!

Live masterclass