$(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 );
- };
随机推荐
- LightOJ 1336 Sigma Function 算数基本定理
题目大意:f(n)为n的因子和,给出 n 求 1~n 中f(n)为偶数的个数. 题目思路:算数基本定理: n=p1^e1*p2^e1 …… pn^en (p为素数): f(n)=(1+p1+p1^2+ ...
- 会话管理---Cookie与Session
会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. 保存会话数据的两种技术:Cookie,Session Cookie是客户端技术, ...
- A convenient way of installing(compiling) VIM with YCM
Ah, while I am still downloading LLVM from github(very slow.. and very large in size). I come with m ...
- Lucene4.X 高级应用
Lucene 简介以及使用 Lucene, 一个基于 Java 的开源的全文搜索工具包,可以方便的嵌入到各种应用系统中,实现针对应用的全文索引以及检索功能.目前是 Apache jakarta 项目 ...
- 随机法解决TSP问题
TSP问题一直是个头疼的问题,但是解决的方法数不胜数,很多的算法也都能解决.百度资料一大堆,但是我找到了代码比较简练的一种.随机法.下面只是个人的看法而已,如果有任何问题虚心接受. 顾名思义,随机法就 ...
- PHP资源类型
在PHP中,我们经常使用到资源类型变量.例如:mysql连接.文件句柄等. 这些变量无法使用标量来表示,那么在Zend内核中是如何将PHP中的资源变量与C语言中的资源衔接的呢? 一.资源变量在PHP中 ...
- OpenCV ——遍历图像方法
转自http://blog.csdn.net/daoqinglin/article/details/23628125 ; y < testImage->height; y++) { uch ...
- Codeforces Round #272 (Div. 1) B 构造 math
http://www.codeforces.com/contest/477/problem/C 题目大意:给你n个集合,每个集合里面有四个数字,他们的gcd是k,输出符合条件的集合中m,m为集合中最大 ...
- nginx php版本隐藏
配置完一台服务器后,并不是就可以高枕无忧了,前不久刚刚爆发的PHP 5.3.9版本的漏洞也搞得人心惶惶,所以说经常关注安全公告并及时升级服务器也是必要的.一般来说,黑客攻击服务器的首要步骤就是收集信息 ...
- spring-jms
http://haohaoxuexi.iteye.com/blog/1893038 理解PooledConnectionFactory.CachingConnectionFactory和SingleC ...