Firefox、Opera 和基于 Webkit 的浏览器有一个文档级事件DOMContentLoaded
,您可以使用document.addEventListener("DOMContentLoaded", fn, false)
.
IE中比较复杂。jQuery 在 IE 中所做的就是onreadystatechange
通过 document.onload 事件的备份来监视特定就绪状态的文档对象。document.onload 在 DOM 准备好之后触发(仅当所有图像都完成加载时),因此它仅用作支持,以防早期事件由于某种原因不起作用。
如果您花一些时间在 Google 上搜索,您会找到执行此操作的代码。我认为最受审查的代码是在像 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();
}
}
},