问题描述
我有一个使用 $(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.
我如何实现我自己的 $(document).ready
不使用jQuery的功能?我知道使用 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
支持,但不是IE8:
There is a standards based replacement,DOMContentLoaded
that is supported by over 98% 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 );
}
这篇关于没有jQuery的$(document).ready等价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!