$(document).ready 相当于没有 jQuery [英] $(document).ready equivalent without jQuery
问题描述
我有一个使用 $(document).ready
的脚本,但它没有使用 jQuery 中的任何其他内容.我想通过删除 jQuery 依赖来减轻它的负担.
I have a script that uses $(document).ready
, but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency.
如何在不使用 jQuery 的情况下实现我自己的 $(document).ready
功能?我知道使用 window.onload
会有所不同,因为 window.onload
在加载所有图像、帧等后触发.
How can I implement my own $(document).ready
functionality without using jQuery? I know that using window.onload
will not be the same, as window.onload
fires after all images, frames, etc. have been loaded.
推荐答案
有一个基于标准的替换,DOMContentLoaded
被超过 99% 的浏览器,虽然不是 IE8:
There is a standards based replacement,DOMContentLoaded
that is supported by over 99% of browsers, though not IE8:
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
jQuery 的原生函数比 window.onload 复杂得多,如下所示.
jQuery's native function is much more complicated than just window.onload, as depicted below.
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 );
}
这篇关于$(document).ready 相当于没有 jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!