$(function(){})的执行过程分析
作者: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 );
};
随机推荐
- 扫描局域网内的ip和主机名
1. 目的 今天发现我配置的一台电脑ip被人占用了,所以准备写个程序扫描一下局域网内所有正在使用的ip和主机名 2. 实现--直接上代码 import time import threading im ...
- UVALive 3027 并查集
#include <cstdio> #include <queue> #include <cstring> #include <iostream> #i ...
- Tomcat服务器
常见的web服务器 1. WebLogic是BEA公司的产品,是目前应用最广泛的web服务器,支持J2EE规范(J2EE里有13种技术),商业产品,收费的.银行,证券等对并发,安全要求高的时候用,一般 ...
- POJ 2182/暴力/BIT/线段树
POJ 2182 暴力 /* 题意: 一个带有权值[1,n]的序列,给出每个数的前面比该数小的数的个数,当然比一个数前面比第一个数小的个数是0,省略不写,求真正的序列.(拗口) 首先想到的是从前到后暴 ...
- 配置App真机测试证书的流程 一览
原文链接:http://www.jianshu.com/p/6b0de0d4c925 有开发者账号的前提下, 请进行如下步骤:1.首先登录网站:https://developer.apple.com. ...
- Android提高第十九篇之"多方向"抽屉--转
本文来自http://blog.csdn.net/hellogv/ ,引用必须注明出处! 在android上要实现类似Launch的抽屉效果,大家一定首先会想起SlidingDrawer.Slidin ...
- ==和equals的异同
== 和 Equals 的区别 1. == 是一个运算符. 2.Equals则是string对象的方法,可以.(点)出来. 我们比较无非就是这两种 1.基本数据类型比较 2.引用对象比较 1.基本数据 ...
- HDU 4612 Warm up(双连通分量缩点+求树的直径)
思路:强连通分量缩点,建立一颗新的树,然后求树的最长直径,然后加上一条边能够去掉的桥数,就是直径的长度. 树的直径长度的求法:两次bfs可以求,第一次随便找一个点u,然后进行bfs搜到的最后一个点v, ...
- 学习笔记——策略模式Strategy
策略模式,与模板模式一样,都是为了将接口和算法实现解耦,但策略模式更主要是整体算法的替换,而模板模式主要是流程一致,部分算法的替换. 个人理解为,一般算法替换,使用策略模式,当算法流程一致,可以提取为 ...
- ios 概况了解
iOS的系统架构分为四个层次:( iOS是基于UNIX内核,android是基于Linux内核) 核心操作系统层(Core OS layer).核心服务层(Core Services layer).媒 ...