这就是 jQuery 包装您正在寻找的函数的方式 - 该代码片段不需要 jQuery,并且是跨浏览器兼容的。我已将对 jQuery.ready() 的所有调用替换为yourcallback
- 您需要定义它。
这里发生了什么:
- 首先,函数
DOMContentLoaded
已定义,它将在 DOMContentLoaded 事件触发时使用 - 它确保回调仅被调用一次。
- 检查文档是否已加载 - 如果是,立即触发回调
- 否则嗅探功能(
document.addEventListener
/ document.attachEvent
)并将回调绑定到它(IE和普通浏览器不同,加上onload回调)
从 jQuery 1.4.3 开始,函数 bindReady() 和 DOMContentLoaded:
/*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
// Cleanup functions for the document ready method
// attached in the bindReady handler
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
//jQuery.ready();
yourcallback();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
//jQuery.ready();
yourcallback();
}
};
}
// 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 );
// ^^ you may want to call *your* function here, similarly for the other calls to jQuery.ready
setTimeout( yourcallback, 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 );
window.addEventListener( "load", yourcallback, 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", yourcallback );
}
这是 51 行纯 JavaScript 代码,只是为了可靠地注册事件。据我所知,没有更简单的方法。去展示像 jQuery 这样的包装器的优点:它们包装了功能嗅探和丑陋的兼容性问题,以便您可以专注于其他事情。