What Is HTML/JS Onload and How Does It Work?

Computer with code on the screen

HTML/JS onload concept can help you to control the behavior of the webpage once it has loaded.


Loading a webpage includes waiting for the page content, images, and other resources to be completely loaded.


Some webpages ensure that certain functionality doesn’t occur until everything has finished loading. An example includes retrieving data from a database only after the page has loaded.

There are different ways you can check if a webpage is fully loaded. You can listen to events using JavaScript event handlers, use the window.onload JavaScript event, or the onload HTML attribute.


How to Use onLoad With the Body HTML Element

You can use JavaScript events to check if the body of the webpage has loaded. You will need an HTML file with some page content and a JavaScript file to execute the code.

The code used in this project is available in a GitHub repository and is free for you to use under the MIT license.

  1. In a new HTML file called index.html, add the following basic HTML code:
     <!DOCTYPE html>
    <html>
      <head>
        <title>Example using onload</title>
      </head>
      <body>
        <h1>Example using onload()</h1>
        <p>This example demonstrates how to use the onload() event in JavaScript.</p>
      </body>
    </html>
  2. Create a new file in the same folder called script.js. Link this file to your HTML page using the script tag. You can add the script tag at the bottom of the body tag:
     <body>
      
      <script src="script.js"></script>
    </body>
  3. Inside the content in your HTML body tag, add an empty paragraph tag.
     <p id="output"></p> 
  4. Inside the JavaScript file, add the window.onload event function. This will execute when the page has loaded:
     window.onload = function() {
      
    };
  5. Inside the function, populate the content of the empty paragraph tag. This will change the paragraph tag to display a message only when the page has loaded:
     document.getElementById("output").innerHTML = "Page loaded!"; 
  6. Alternatively, you can also use an event listener to listen for the DOMContentLoaded event. DOMContentLoaded triggers earlier than window.onload. It triggers as soon as the HTML document is ready, rather than waiting for all the external resources to load.
     document.addEventListener('DOMContentLoaded', function() {
      document.getElementById("output").innerHTML = "Page loaded!";
    });
  7. Open the index.html file in a web browser, to view the message when the page finishes loading:
    HTML page loaded in browser

  8. Instead of using JavaScript events to check if a page has loaded, you can also use the onload HTML attribute for the same result. Add the onload attribute to the body tag in your HTML file:
     <body onload="init()"> 
  9. Create the init() function inside the JavaScript file. It is not recommended to use both the onload HTML attribute and onload JavaScript event at the same time. Doing so could lead to unexpected behavior or conflicts between the two functions.
     function init() {
      document.getElementById("output").innerHTML = "Page loaded!";
    }

We recommend using the JavaScript event listeners and the window.onload method over the HTML onload attribute because keeping the behavior and content of the webpage separate is a good practice. Also, the JavaScript event listeners provide more compatibility and flexibility over the other two methods.

How to Use onLoad With the Image HTML Element

You can also use the onload event to execute code when other elements load on the page. An example of this is the image element.

  1. Inside the same folder as your index.html file, add any image.
  2. Inside the HTML file, add an image tag, and link the src attribute to the name of the image saved in the folder.
     <img id="myImage" src="Pidgeymon.png" width="300"> 
  3. Add another empty paragraph tag to display a message when the image loads:
     <p id="imageLoadedMessage"></p> 
  4. Inside the JavaScript file, add an onload event on the image. Use the unique id myImage to determine which image element to add the onload event to:
     var myImage = document.getElementById("myImage");
    myImage.onload = function() {

    };
  5. Inside the onload event, change the inner HTML to add the Image loaded message:
     document.getElementById("imageLoadedMessage").innerHTML = "Image loaded!"; 
  6. Instead of using myImage.onload, you can also use an event listener to listen to the load JavaScript event:
     myImage.addEventListener('load', function() {
      document.getElementById("imageLoadedMessage").innerHTML = "Image loaded!";
    });
  7. Open index.html in a web browser to view the image and message:
    HTML image loaded in browser

  8. For the same result, you can also use the onload HTML attribute. Similar to the body tag, add an onload attribute to the img tag:
     <img id="myImage" src="Pidgeymon.png" width="300" onload="imageLoaded()"> 
  9. Add the function in the JavaScript file, to execute the code when the image has loaded:
     function imageLoaded() {
      document.getElementById("imageLoadedMessage").innerHTML = "Image loaded!";
    }

How to Use onLoad When Loading the JavaScript

You can use the HTML onload attribute to check if the browser has finished loading the JavaScript file. There is no equivalent JavaScript onload event for the script tag.

  1. Add the onload attribute to the script tag in your HTML file.
     <script src="script.js" onload="LoadedJs()"></script> 
  2. Add the function to your JavaScript file. Print a message by logging to the browser console:
     function LoadedJs() {
      console.log("JS Loaded by the browser!");
    }
  3. Open the index.html file in the browser. You can use Chrome DevTools to view any messages output into the console.
    Browser with console message

Loading Webpages in the Browser

Now you can use functions and events to execute certain code when a webpage has completed loading. Loading pages are a big factor in creating a smooth and seamless user experience.

You can learn more about how you can integrate more interesting loading page designs into your website.

Total
0
Shares
Leave a Reply
Previous Article
Ali Wong, Steven Yeun 'Broke Out in Hives' After Filming 'Beef'

Ali Wong, Steven Yeun 'Broke Out in Hives' After Filming 'Beef'

Next Article
4 Ways Meal Prepping Might Be Affecting Your Health

Don't Eat the Same Meals Each Week. It's Impacting Your Health

Related Posts