作者:zccst

首先,$(function(){})是$(document).ready(function(){})的简写形式。

在日常使用中,我们会把代码写到$(function(){})中,今天看看jQuery是如何做的(过程有点长)。

1,看jQuery入口,结论是$(function(){})是$(document).ready(function(){})的简写形式

$(function(){})相对于$()中传入了一个function类型的数据。根据源码:

jQuery.fn = jQuery.prototype = {

init:function( selector, context, rootjQuery ) {

if ( jQuery.isFunction( selector ) ) {
            return rootjQuery.ready( selector );
        }

}

}

而rootjQuery就是$(document),见866行源码

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

2,$(document).ready(function(){})是如何实现的呢?

从$().ready()的调用方式可以看出,ready是对象方法,见240行源码

ready: function( fn ) {
    // Add the callback
    jQuery.ready.promise().done( fn );

return this;
},

可以看出,jQuery.ready.promise()是一个对象,调用了done(fn)方法,表明调用了一个延迟对象,再看一下jQuery.ready.promise()

 jQuery.ready.promise = function( obj ) {
if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );//调用工具方法jQuery.ready } else { // Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );//回调函数在90行,也调用工具方法jQuery.ready
}
}
return readyList.promise( obj );
};

随机推荐

  1. 判断是ios还是android

    //判断是ios还是androidvar system;var ua = navigator.userAgent.toLowerCase(); if (/iphone|ipad|ipod/.test( ...

  2. call_grant_dml.sql

    set echo offpromptprompt =========================================================================== ...

  3. hdu 5532

    input 1<=T<=2000 2<=n<=10e5 a1 a2 ... an 1<=ai<=10e5 最多二十个n>1000 output 能否从数组中移 ...

  4. thrift概述

    Apache Thrift 是FaceBook实现的一种跨平台的远程服务调用(RPC)的框架.它采用接口描述语言(IDL)定义并创建服务,传输数据采用二进制格式,相对于XML和Json等常用数据传输方 ...

  5. more分页阅读

    相比cat命令,more可以更加灵活的去阅读查看文件. 1.命令格式 more [-dlfpcsu ] [-num ] [+/ pattern] [+ linenum] [file ... ] 2.命 ...

  6. C/C++ kubetu

    reference sign & use predefine in c, but const in c++

  7. Loadrunner之文件的上传(八)

    老猪提供: https://mp.weixin.qq.com/s?__biz=MzIwOTMzNDEwNw==&mid=100000013&idx=1&sn=624f5bc74 ...

  8. GameUnity 2.0 文档(四) 网格+四叉树 最优碰撞检测

    在写之前,必须对 前一篇文档补充一下. Camera2DAngle类是 摄像机旋转 2d人物360度,PlayerMove是人物移动. 这两个类 都可以 360 °  场景旋转人物也跟着旋转. 但不能 ...

  9. lucene 中关于Store.YES 关于Store.NO的解释

    总算搞明白 lucene 中关于Store.YES  关于Store.NO的解释了 一直对Lucene Store.YES不太理解,网上多数的说法是存储字段,NO为不存储. 这样的解释有点郁闷:字面意 ...

  10. [LeetCode] Magical String 神奇字符串

    A magical string S consists of only '1' and '2' and obeys the following rules: The string S is magic ...