jQuery:理解$(document).ready()的特殊写法

简介:

看书时注意到下面两条语句的功效是相同的,

 
  1. $(function(){alert("hello!");});  
  2. $(document).ready(function(){alert("hello!");}); 

这个特殊写法就是用$()代替$(document).ready(),类似于(有差异)window.onload弹出个窗口:

 

查看jQuery1.8.3源代码,是这样封装的:

 
  1. (function( window, undefined ) {  
  2.     /*...jQuery源代码全部都在这里了...*/ 
  3. })( window );  

下列语句把封装在内部的jQuery先赋给window.$,紧接着再赋给window.jQuery。这意味着在实际使用时window.$和window.jQuery是一回事。因为$这个符号只有1个字母,比jQuery短,所以更常用一些,但要注意到$非jQuery所独有,节约字母的代价是增加了命名冲突的风险。

 
  1. // Expose jQuery to the global object  
  2. window.jQuery = window.$ = jQuery; 

下面是jQuery的初始化语句(注意到此时函数并未执行):

 
  1. // Define a local copy of jQuery  
  2. jQuery = function( selector, context ) {  
  3.     // The jQuery object is actually just the init constructor 'enhanced'  
  4.     return new jQuery.fn.init( selector, context, rootjQuery );  

找到jQuery.fn的定义,这是一个对象,其中有一个叫init的函数元素: 

 
  1. jQuery.fn = jQuery.prototype = {  
  2.     constructor: jQuery,  
  3.     init: function( selector, context, rootjQuery ) {  
  4.         var match, elem, ret, doc;  
  5.  
  6.         // Handle $(""), $(null), $(undefined), $(false)  
  7.         if ( !selector ) {  
  8.             return this;  
  9.         }  
  10.  
  11.         // Handle $(DOMElement)  
  12.         if ( selector.nodeType ) {  
  13.             this.context = this[0] = selector;  
  14.             this.length = 1;  
  15.             return this;  
  16.         }  
  17. /*...以下省略...*/ 

继续下去,init中有一段逻辑:

 
  1. // HANDLE: $(function)  
  2. // Shortcut for document ready  
  3. else if ( jQuery.isFunction( selector ) ) {  
  4.     return rootjQuery.ready( selector );  

晕了晕了,rootjQuery的定义又回到了jQuery:

 
  1. // All jQuery objects should point back to these  
  2. rootjQuery = jQuery(document); 

有点递归的意思了,嗯,就是递归。jQuery不仅仅是一个函数,而且还是一个递归函数。

如果调用jQuery时输入的是一个函数,例如文章开头提到的:

 
  1. $(function(){alert("hello!");}); 

那么这个函数就会走到rootjQuery那里,再回到jQuery,执行jQuery(document).ready。而$与jQuery是一回事,这样就解释了$(inputFunction)可以代替$(document).ready(inputFunction)。

现在还不想结束此文,我的问题是$(document)做了什么?嗯,还是要进入到jQuery.fn.init,确认存在nodeType属性,达到Handle $(DOMElement)”的目的。怎么Handle呢?具体就是把输入参数(此时为document)赋值给this的context属性,然后再返回this。也就是说,$(document)执行完了返回的还是jQuery,但是情况发生了变化,具体就是context属性指向了输入参数(此时为document)暂时还不明白绕这么大个圈子为context(上下文)属性赋值有何意义?

接下去的问题可能会是$(document).ready和window.onload的区别?提取ready函数的定义如下:

 
  1. ready: function( fn ) {  
  2.     // Add the callback  
  3.     jQuery.ready.promise().done( fn );  
  4.  
  5.     return this;  
  6. }, 

阅读代码探究promise是有点晕啊,想到自己的iJs工具包了,打印jQuery.ready.promise()如下:

    [Object] jQuery.ready.promise()
        |--[function] always
        |--[function] done
        |--[function] fail
        |--[function] pipe
        |--[function] progress
        |--[function] promise
        |--[function] state
        |--[function] then

进一步打印整理done函数代码如下(这下彻底晕了~~):

 
  1. function() {   
  2.     if ( list ) {   
  3.         // First, we save the current length   
  4.         var start = list.length;   
  5.         (function add( args ) {   
  6.             jQuery.each( args, function( _, arg ) {   
  7.                 var type = jQuery.type( arg );   
  8.                 if ( type === "function" ) {   
  9.                     if ( !options.unique || !self.has( arg ) ) { list.push( arg ); }   
  10.                 } else if ( arg && arg.length && type !== "string" ) {   
  11.                     // Inspect recursively add( arg );   
  12.                 }   
  13.             });   
  14.         })( arguments );   
  15.         // Do we need to add the callbacks to the   
  16.         // current firing batch?   
  17.         if ( firing ) {   
  18.             firingLength = list.length;   
  19.             // With memory, if we're not firing then   
  20.             // we should call right away   
  21.         } else if ( memory ) {   
  22.             firingStart = start; 
  23.        fire( memory );   
  24.         }   
  25.     }   
  26.     return this;   

好在代码不长,看起来关键就在于fire函数了。嗯,找回一丝清醒了。在上面的done函数里面可以注意到使用了默认的arguments变量,将注入的函数push到了list数组。下面是fire函数:

 
  1. fire = function( data ) {  
  2.     memory = options.memory && data;  
  3.     fired = true;  
  4.     firingIndex = firingStart || 0;  
  5.     firingStart = 0;  
  6.     firingLength = list.length;  
  7.     firing = true;  
  8.     for ( ; list && firingIndex < firingLength; firingIndex++ ) {  
  9.         if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {  
  10.             memory = false// To prevent further calls using add  
  11.             break;  
  12.         }  
  13.     }  
  14.     firing = false;  
  15.     if ( list ) {  
  16.         if ( stack ) {  
  17.             if ( stack.length ) {  
  18.                 fire( stack.shift() );  
  19.             }  
  20.         } else if ( memory ) {  
  21.             list = [];  
  22.         } else {  
  23.             self.disable();  
  24.         }  
  25.     }  

可以看到代码中对list数组里面使用了apply。用iJs包调试可发现data[0]就是document对象,也就是说,调用$(myFunction)的结果是在document对象上执行了myFunction因为list是个数组,所以也就不难理解$()其实是多次输入,一次执行。

最后,回过头来阅读promise源代码,关于$()输入函数的执行时机的秘密就在这里了:

 
  1. jQuery.ready.promise = function( obj ) {  
  2.     if ( !readyList ) {  
  3.  
  4.         readyList = jQuery.Deferred();  
  5.  
  6.         // Catch cases where $(document).ready() is called after the browser event has already occurred.  
  7.         // we once tried to use readyState "interactive" here, but it caused issues like the one  
  8.         // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15  
  9.         if ( document.readyState === "complete" ) {  
  10.             // Handle it asynchronously to allow scripts the opportunity to delay ready  
  11.             setTimeout( jQuery.ready, 1 );  
  12.  
  13.         // Standards-based browsers support DOMContentLoaded  
  14.         } else if ( document.addEventListener ) {  
  15.             // Use the handy event callback  
  16.             document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );  
  17.  
  18.             // A fallback to window.  
  19.             window.addEventListener( "load", jQuery.ready, false );  
  20.  
  21.         // If IE event model is used  
  22.         } else {  
  23.             // Ensure firing before   
  24.             document.attachEvent( "onreadystatechange", DOMContentLoaded );  
  25.  
  26.             // A fallback to window.  
  27.             window.attachEvent( "onload", jQuery.ready );  
  28.  
  29.             // If IE and not a frame  
  30.             // continually check to see if the document is ready  
  31.             var top = false;  
  32.  
  33.             try {  
  34.                 top = window.frameElement == null && document.documentElement;  
  35.             } catch(e) {}  
  36.  
  37.             if ( top && top.doScroll ) {  
  38.                 (function doScrollCheck() {  
  39.                     if ( !jQuery.isReady ) {  
  40.  
  41.                         try {  
  42.                             // Use the trick by Diego Perini  
  43.                             // http://javascript.nwbox.com/IEContentLoaded/  
  44.                             top.doScroll("left");  
  45.                         } catch(e) {  
  46.                             return setTimeout( doScrollCheck, 50 );  
  47.                         }  
  48.  
  49.                         // and execute any waiting functions  
  50.                         jQuery.ready();  
  51.                     }  
  52.                 })();  
  53.             }  
  54.         }  
  55.     }  
  56.     return readyList.promise( obj );  
  57. }; 

从代码的注释中可以看到这段代码在消除bug的过程中还是颇费了些心思的。查看其中一个网址http://bugs.jquery.com/ticket/12282#comment:15,是关于IE9/10的一个bug(document ready is fired too early on IE 9/10),好在已经解决。

绕了这么多弯子,整个事情看起来就是这样,如果每一个浏览器都能有document.readyState === "complete",就简单了。再看到$(),要感谢编写jQuery的大神们(以及其他类似框架的大神们),是他们的努力,让世界变得完美。






 本文转自 hexiaini235 51CTO博客,原文链接:http://blog.51cto.com/idata/1119589,如需转载请自行联系原作者


相关文章
|
7月前
|
JavaScript 测试技术
探索jQuery的ready方法比原生js的window.onload快的奥秘
探索jQuery的ready方法比原生js的window.onload快的奥秘
|
4月前
|
JavaScript
jQuery学习(四)— jQuery的ready事件和原生JS的load事件的区别
jQuery学习(四)— jQuery的ready事件和原生JS的load事件的区别
|
4月前
|
JavaScript
jQuery学习(一)—jQuery应用步骤以及ready事件和load事件的区别
jQuery学习(一)—jQuery应用步骤以及ready事件和load事件的区别
|
JavaScript
Jquery中的$(document).ready()详解
1.$(document).ready()的作用 $(document).ready(function(){.... })这个函数的作用和window.onload差不多,不同的是 (1)onload()的方法是在页面加载完成后才发生,这包括DOM元素和其他页面元素(例如图片)的加载 (2)$(document).ready()所要执行的代码是在DOM元素被加载完成的情况下执行,所以,使用document.ready()方法的执行速度比onload()的方法要快。
|
JavaScript
Dom onload和jQuery document ready的区别
Dom onload和jQuery document ready的区别
Dom onload和jQuery document ready的区别
|
JavaScript
HTML里Dom onload和jQuery document ready这两个事件的区别
HTML里Dom onload和jQuery document ready这两个事件的区别
107 0
HTML里Dom onload和jQuery document ready这两个事件的区别
|
Web App开发 JavaScript 前端开发
jquery $(document).ready() 与window.onload的区别
<p><span style="font-family:Tahoma,Helvetica,Arial,宋体,sans-serif; font-size:14px; line-height:14px; text-indent:30px; background-color:rgb(247,252,255)">Jquery中$(document).ready()的作用类似于传统JavaScrip
1452 0