$(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 );
};
随机推荐
- 多线程进阶之并发工具类:CountDownLatch、CyclicBarrier
并发工具类在java.util.concurrent包下.常用的有CountDownLatch.CyclicBarrier,用它们可以控制并发流程. 1.CountDownLatch探究: 主要用到其 ...
- 基于Sublime Text搭建Python IDE
http://loosky.net/2967.html(包括SublimeREPL插件的安装和设置快捷键) SublimeCodeIntel,智能提示功能,查找自定义函数引用的快捷键--Alt+鼠标左 ...
- js所有函数集合
lick() 对象.click() 使对象被点击. closed 对象.closed 对象窗口是否已关闭true/false clearTimeout(对象) 清除已设置的setTimeout对象 c ...
- php使用curl提交xml数据
$xml_data ='<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_ ...
- mysql建表: 主键,外键约束
CREATE DATABASE db_studentinfo; USE db_studentinfo ; DROP TABLE IF EXISTS t_student ; CREATE TABLE t ...
- Servlet程序开发--Servlet 与 表单
servlet程序: doPost方法时为了防止表单提交时post方式的问题.否则只能处理get请求 package org.lxh.servletdemo ; import java.io.* ; ...
- Intergate flot with Angular js ——Angular 图形报表
下面这篇文章最终的结论就是 Flot 插件 结合 Angular 的Directive 来处理 图表的绘制 给出github上的一个demo源码.https://gist.github.com/fly ...
- 【第k小素数 】 打表问题
Prime Number TimeLimit: 1 Second MemoryLimit: 32 Megabyte Totalsubmit: 399 Accepted: 88 Description ...
- Fragment和Activity(转)
Android Fragment和Activity Fragment和Activity Fragment和Activity的交互 一个Fragment的实例总是和包含它的Activity直接相关. f ...
- [转]makefile文件的编写规则及实例
http://xueqi.iteye.com/blog/1567866 1.一个简单的makefile例子 假设一个程序有两个文件file1.c,file2.c,每个文件都包含head.h,生 ...