$(document).ready vs window.load

By : Admin  |  Updated On : 18 Sep, 2020

$(document).ready vs window.load

Introduction to $(document).ready(function(){})$(window).on('load', function(){});

 

$(document).ready(function(){})

The document ready event occurs just after document is loaded like DOM(document) object is created. It is automatically fire when dom is ready. All the dom object scripts goes inside this function.

$(document).ready(function(){
   //all code goes here
})

 

$(window).on('load', function(){})

The window onload event occurs when all the resources of the page loaded. like images,css,js etc. 

We use window onload when any external script is dependent page code.

$(window).on('load', function(){
    //all code goes here
})

Note : Above jquery window onload code can be only one in the page if we write twice last code will be executed, to overcome this issue we need to write javascript addEventListener function like below.

Below code will execute one by one.

window.addEventListener('load', (event) => {
    //console.log('The page has fully loaded');
});


window.addEventListener('load', (event) => {
    //console.log('The page has fully loaded');
});