作者: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. Struts中的数据处理的三种方式

    Struts中的数据处理的三种方式: public class DataAction extends ActionSupport{ @Override public String execute() ...

  2. linux视频学习(简单介绍)20160405

    看一周学会linux系统的学习笔记. 1.linux系统是一个安全性高的开源,免费的多用户多任务的操作系统. 2.linux工作分为linux系统管理员,linux程序员(PC上软件开发,嵌入式开发) ...

  3. 8633 回文划分(dp)

    8633 回文划分 该题有题解 时间限制:1000MS  内存限制:1000K提交次数:169 通过次数:63 题型: 编程题   语言: G++;GCC Description 我们说一个字符串是回 ...

  4. eclipse,android Localization (Internationalization) 安卓本地化(国际化)

    1.创建新的资源文件,名字保持一致.提示"已存在",继续. 2.使用“语言”作为识别器,然后选择相应的语言代码.Tips:其他的适配,如国家.屏幕大小等,也是通过这里的识别器实现适 ...

  5. Git 使用初体验

    http://my.oschina.net/moooofly/blog/228608 很久之前在 http://git.oschina.net/ 上创建了一个私有项目 modb ,目的主要是用来学习如 ...

  6. angularjs中动态为audio绑定src

    今天在angularjs中用audio的时候碰到的这些问题,查阅http://www.cnblogs.com/rachelanlan/p/3598070.html获得解决,感谢! <div cl ...

  7. MoQ(基于.net3.5,c#3.0的mock框架)简单介绍

    我们在做单元测试的时候,常常困扰于数据的持久化问题,很多情况下我们不希望单元测试影响到数据库中的内容,而且受数据库的影响有时我们的单元测试的速度会很慢,所以我们往往希望将持久化部分隔离开,做单元测试的 ...

  8. 禁止root远程登录

    Linux禁止root远程登录 ssh的修改vi /etc/ssh/sshd_config将默认的#PermitRootLogin yes去注释改为PermitRootLogin no service ...

  9. jquery给img添加按钮事件

    1. img控件加id <a href="#"><img width="20" height="20" id=" ...

  10. css link import

    link和@import的区别   页面中使用CSS的方式主要有3种:行内添加定义style属性值,页面头部内嵌调用和外面链接调用,其中外面引用有两种:link和@import.外部引用CSS两种方式 ...