jQuery中的加载:
$(function(){
alert(1);
});
调用的是rootjQuery.ready( selector );其中rootjQuery = jQuery(document);所以上述代码可以写成:
$(document).ready(function(){
alert(1);
});
$().ready()中的ready()是实例方法:
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
fn就是function(){alert(1)},被添加到延迟对象中,等待被触发。
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" ) {//DOM加载已经完成,直接调用
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );//加延迟是针对IE
} else {//dom加载未完成,进行监听
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
//有缓存时,先出发load,在触发DOMContentloaded
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
等DOM加载完成后,会调用computed函数:最后直线工具方法
jQuery.ready()
completed = function() {//保证jQuery.ready()只触发一次
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
工具方法jQuery.ready():
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
}
其中readyList.resolveWith( document, [ jQuery ] );会执行前面的fn函数,function(){alert(1)}
$(function(arg){
console.log(this);//document对象
console.log(arg);//jQuery函数
});
$.holdReady(true);
$(function(){
alert(1);
});
上述代码不会弹出 1。
这个工具方法的用途:等a.js加载执行完后,在执行$(function(){alert(1);});
$.holdReady(true);
$.getScript("a.js",function(){
$.holdReady(false)
})
$(function(){
alert(1);
});
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
}