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