DOM - Load event (onload, load listener)

About

The load event 1) is an event that is fired / emitted on:

Possible duplicate of Web Browser - Load Event

Event Handling

To ensure that the code runs after the browser finishes loading the page or any element such as an image or script, you may listen to the load event the following way:

  • with a load event listener
  • with the onLoad attribute

load Event Listener

With the load event listener

window.addEventListener

When the window has finished loading (ie document, image, script, …). ie when the page load has finished

This state is also known as the loaded state ie

Example:

window.addEventListener("load", function(event) {
    console.log("EventListener: The page is loaded (ie window is loaded)");
});

Element.addEventListener

The below example uses an image but you can use it on any HTML element that fetches resources such as script, link, …)

Example:

  • An image
<img src="https://datacadamia.com/_media/lenna.png" alt="Lenna" width="150">
  • The script that we want to run after the image has loaded
document.querySelector("img").addEventListener("load", () => console.log("Lenna has loaded") );

onLoad attribute

HTML element onLoad

The below example uses an image but you can use it on any HTML element that fetches resources such as script, link, …)

  • An image
<img src="https://datacadamia.com/_media/lenna.png" alt="Lenna" width="150" onload="lennaHasLoaded(event)">
  • The script that we want to run after the image has loaded
function lennaHasLoaded(){
 console.log("Lenna has loaded");
}

window.onload

The onload attribute supports only one function that will be executed after the load event.

You should not use it because any script can overwrite it.

Example: the first function sets on the onload window property below will not be executed.

  • First function
window.onload = function() {
     console.log("window.onload: All resources finished loading! First function that will not be executed");
};
  • Second execution
window.onload = function() {
     console.log("window.onload: All resources finished loading! Second and last function that have been set.");
};

Other

Jquery

On load Demo:

$(window).on("load", function() {
   console.log("The page has fully loaded");
});

Old browser

This code is for informational purpose only. It uses the onreadystatechange of the XHR request

script.onreadystatechange = function () {
   if (this.readyState === 'loaded') callback();
}
script.onload = callback;

Powered by ComboStrap