How to use Document onload in JavaScript

In this tutorial, we will go through how to execute a function when the page has loaded in JavaScript using onload.

 

window.onload Example

The JavaScript window.onload utility will fire when all the content in the page has loaded including images, CSS, scripts .etc. Here is an example that will run a function containing an alert() message:

 

window.onload = function() {
  alert('Loaded!');
};

 

Here is another example using addEventListener:

 

window.addEventListener("load", function(){
  alert('Loaded!');
});

 

document.onload Example

The document.onload utility will fire when the DOM is read, excluding images and external content.

 

document.onload = function() {
  alert('Loaded!');
};

 

jQuery Document onload Example

If you're using jQuery, here is an example of how to create a function that will run on DOM loaded:

 

$(document).ready(function() {
  /* code to run */
});

 

Here is another example using addEventListener:

 

document.addEventListener("DOMContentLoaded", function(){
  alert('Loaded!');
});

 

The difference with document object is it uses the DOMContentLoaded property to indicate the DOM has loaded.