DOM - Document Loaded - onload event

About

A document is in the loaded state once:

A document is in a ready state, all images are not finished downloading, including banner ads.

When the page is in this state the load event is emitted.

Event

To ensure that the code runs after the browser finishes loading the document or an image, you may listen to the load event the following way.

Element: onLoad attribute

  • 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");
}

Document

window.addEventListener

DOM - Event Listener

window.addEventListener("load", function(event) {
    console.log("EventListener: All resources finished loading!");
});

window.onload

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

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

For instance, 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.");
};

Jquery

On load Demo:

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

On Load Solution

function func1() {
  alert("This is the first.");
}

function func2() {
  alert("This is the second.");
}


function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(func1);
addLoadEvent(func2);

addLoadEvent(function() {
    document.body.style.backgroundColor = '#EFDF95';
})

Reference


Powered by ComboStrap