$(document).ready vs $(window).load vs window.onload

原文地址: $(document).ready vs $(window).load vs window.onload

$(document).ready

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

$(window).load

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

window.onload

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 onload="myFunction"></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 onload="myFunction()">
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" onload="myImageFunction()">
4 
5 // // myFunction() which will call on image load
6 function myImageFunction(){
7    alert("call on image load");
8 }

 window.onload  Examples

The function fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

1 window.onload = function() {
2   init();
3   doSomethingElse();
4 };

 以上です。

posted @ 2015-12-16 17:28  提佰萬  阅读(466)  评论(0编辑  收藏  举报