Firefox、Opera 和基于 Webkit 的浏览器有一个文档级事件DOMContentLoaded
,您可以使用document.addEventListener("DOMContentLoaded", fn, false)
.
在 IE 中更复杂。jQuery 在 IE 中所做的是onreadystatechange
通过 document.onload 事件的备份监视文档对象的特定就绪状态。document.onload 在 DOM 准备好之后触发(仅当所有图像都完成加载时),因此它仅用作防止早期事件由于某种原因不起作用的情况。
如果您花一些时间谷歌搜索,您会找到执行此操作的代码。我认为要做到这一点的最经过审查的代码是在像 jQuery 和 YUI 这样的大型框架中,所以,即使我没有使用那个框架,我也会查看他们的源代码以获取技术。
这是 jQuery 1.6.2 源代码的主要部分document.ready()
:
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// 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 );
}
// 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 );
// 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 );
// 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();
}
}
},