首页 > 代码库 > $(function(){})的执行过程分析
$(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()
1 jQuery.ready.promise = function( obj ) { 2 if ( !readyList ) { 3 4 readyList = jQuery.Deferred(); 5 6 // Catch cases where $(document).ready() is called after the browser event has already occurred. 7 // we once tried to use readyState "interactive" here, but it caused issues like the one 8 // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 9 if ( document.readyState === "complete" ) { 10 // Handle it asynchronously to allow scripts the opportunity to delay ready 11 setTimeout( jQuery.ready );//调用工具方法jQuery.ready 12 13 } else { 14 15 // Use the handy event callback 16 document.addEventListener( "DOMContentLoaded", completed, false ); 17 18 // A fallback to window.onload, that will always work 19 window.addEventListener( "load", completed, false );//回调函数在90行,也调用工具方法jQuery.ready 20 } 21 } 22 return readyList.promise( obj ); 23 };