原文地址: $(document).ready vs $(window).load vs window.onload
We execute our code when DOM is ready except images.
1 //call type 1 2 $(document).ready(function() { 3 /** work when all HTML loaded except images and DOM is ready **/ 4 // your code 5 }); 6 7 //call type 2 8 $(function() { 9 /** work when all HTML loaded except images and DOM is ready **/ 10 //your code 11 }); 12 13 //call type 3 14 $(document).on(‘ready‘, function(){ 15 /** work when all HTML loaded except images and DOM is ready **/ 16 //your code 17 }); 18 19 //call type 4 20 jQuery(document).ready(function(){ 21 /** work when all HTML loaded except images and DOM is ready **/ 22 //your code 23 });
It is work when all DOM is ready including images so it is useful when on document load we want to work with images.
1 $(window).load(function() { 2 /** this is come when complete page is fully loaded, including all frames, objects and images **/ 3 });
The onload event is a standard event in the DOM, while above two are specific to jQuery . this is also same functionality like $(window).load
but window.onload
is the built-in JavaScript event.The onload event occurs when an object has been loaded.like if we take a example of image and call onload event in image tag then it will call when image will load .generally we use it in body tag.
In HTML
1 <element ></element>
In JS
1 object.onload=function(){/**your desire code**/};// here object can be window,body and etc
1) Here alert “call on body load” call immediately after body has been loaded
1 // In HTML 2 <!-- on body onload call myFunction --> 3 <body > 4 5 //In JavaScript 6 // myFunction() which will call on body load 7 function myFunction(){ 8 alert("call on body load"); 9 }
2) Here alert “call on image load” call immediately after image has been loaded
1 // In HTML 2 <!-- on image onload call myImageFunction() --> 3 <img src="image path src" > 4 5 // // myFunction() which will call on image load 6 function myImageFunction(){ 7 alert("call on image load"); 8 }