作者: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. 网络获取的XML的Pull解析

    <?xml version="1.0" encoding="utf-8" ?> - <students> - <student x ...

  2. acm课程练习2--1013(同1014)

    题目描述 There is a strange lift.The lift can stop can at every floor as you want, and there is a number ...

  3. #ifndef 和 #endif

    文件中的#ifndef 头件的中的#ifndef,这是一个很关键的东西.比如你有两个C文件,这两个C文件都include了同一个头文件.而编译时,这两个C文件要一同编译成一个可运行文件,于是问题来了, ...

  4. ubuntu11.10server 安装php-redis插件

    1.下载php-redis插件 1 sudo wget https://github.com/nicolasff/phpredis/archive/master.zip 2.安装 1 2 3 4 5 ...

  5. BootStrap详解之(一)

    一.BootStrap简介 BootStrap是一个用来构建网站前段框架的一个插件.无论你是想构建应用程序.博客还是CMS网站,Bootstrap都特别的使用,只要你想得到,它就能行.Bootstra ...

  6. psy & obv

    PSY和OBV 1,PSY心理线是投资者对股市涨跌产生心理波动的情绪指标.相反,当PSY曲线向下跌破PSYMA曲线后,为卖出时机..当PSY曲线向上突破PSYMA曲线后,开始向下回调至PSYMA曲线, ...

  7. WordPress常用插件

    1.Remove Open Sans font Link from WP core 由于Wordpress后台外链加载了谷歌字体(代码位置在wordpress\wp-includes\script-l ...

  8. stdarg.h头

    stdarg.h 头文件,主要目的是让函数可以接受可变参数. va_list :用来保存宏va_arg与宏va_end所需信息. va_start :使va_list指向起始的参数 va_arg :检 ...

  9. docker k8s 1.3.8 + flannel

    docker k8s + flannel kubernetes 是谷歌开源的 docker 集群管理解决方案. 项目地址: http://kubernetes.io/ 测试环境: node-1: 10 ...

  10. Android Studio的使用(三)--包不分级、修改包名

    1.如果不喜欢将包逐级展开的话,可以将每一个包名都完整展现出来,只需要勾选Flatten Packages. 2.修改包名 3.填写新的包名 4.点击确认