cio*_*Pep 8 javascript browser jquery
jquery是如何实现的$(document).ready()?
当然我可以阅读代码,但我正在寻找这个概念......
小智 22
概念:jQuery.ready
虽然JavaScript提供了在呈现页面时执行代码的加载事件,但在完全接收到所有资产(如图像)之前,不会触发此事件.在大多数情况下,只要完全构造DOM层次结构,就可以运行脚本.传递给.ready()的处理程序保证在DOM准备好后执行,因此这通常是附加所有其他事件处理程序并运行其他jQuery代码的最佳位置.使用依赖于CSS样式属性值的脚本时,在引用脚本之前引用外部样式表或嵌入样式元素很重要.
它根据浏览器(IE,例如,不同)实现它,但是在一些特殊情况下,例如在加载DOM 之后调用它时.(我不确定如何在不查看来源的情况下回答这个问题).
jQuery.ready的核心(设置事件绑定的东西是):
bindReady: function() {
Run Code Online (Sandbox Code Playgroud)
只绑定一次.
if ( readyBound ) {
return;
}
readyBound = true;
Run Code Online (Sandbox Code Playgroud)
确保处理在 "DOM加载" 之后调用ready的情况.
// 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 );
}
Run Code Online (Sandbox Code Playgroud)
W3C标准事件模型.
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
Run Code Online (Sandbox Code Playgroud)
老派后备.
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
老派后备.
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
Run Code Online (Sandbox Code Playgroud)
更多行为使其在不同的环境中与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();
}
}
},
Run Code Online (Sandbox Code Playgroud)
doScrollCheck在IE中设置一个"轮询",只有在成功条件成功时才会调用处理程序.有关详细信息,请参阅源代码(它使用IE的怪癖).
快乐的编码.
| 归档时间: |
|
| 查看次数: |
5039 次 |
| 最近记录: |