概念:jQuery.ready http://api.jquery.com/ready/
虽然 JavaScript 提供了在渲染页面时执行代码的 load 事件,但只有在完全接收到所有资源(例如图像)后,才会触发该事件。在大多数情况下,一旦 DOM 层次结构完全构建完毕,脚本就可以运行。传递给 .ready() 的处理程序保证在 DOM 准备好后执行,因此这通常是附加所有其他事件处理程序并运行其他 jQuery 代码的最佳位置。当使用依赖 CSS 样式属性值的脚本时,在引用脚本之前引用外部样式表或嵌入样式元素非常重要。
它根据浏览器实现它(例如,IE是不同的),但在一些特殊情况下,例如调用它时afterDOM 已加载。 (我不知道如何回答这个问题without查看源代码)。
jQuery.ready 的核心 http://code.jquery.com/jquery-1.5.1.js(设置事件绑定的是):
bindReady: function() {
仅绑定一次。
if ( readyBound ) {
return;
}
readyBound = true;
确保处理调用 Ready 的情况after“DOM 加载”。
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
W3C 标准事件模型。
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
老派的后备。
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
IE 事件模型(Opera 也可能使用此模型)。
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
老派的后备。
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
更多行为使其在不同环境下与 IE 保持一致。请注意,事件绑定用于“onreadystatechange”
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
doScrollCheck
在 IE 中设置一个“轮询”,仅当成功条件成功时才会调用处理程序。有关详细信息,请参阅源代码(它使用 IE 的一个特性)。
快乐编码。