我有一个使用 $(document).ready
的脚本,但它没有使用 jQuery 中的任何其他内容。我想通过删除 jQuery 依赖来减轻它。
如何在不使用 jQuery 的情况下实现自己的 $(document).ready
功能?我知道使用 window.onload
会有所不同,因为 window.onload
在所有图像、帧等都已加载后触发。
最佳答案
有一个基于标准的替换,DOMContentLoaded
,超过 99% of browsers 支持,虽然不是 IE8:
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
jQuery 的原生函数比 window.onload 复杂得多,如下图所示。
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
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", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){
if ( jQuery.isReady ) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
jQuery.ready();
})();
}
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}
关于javascript - $(document).ready 没有 jQuery 的等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/799981/