我有一个使用$(document).ready
的脚本,但它没有使用jQuery中的任何其他内容。我想通过删除jQuery依赖来减轻它的影响。
如何在不使用jQuery的情况下实现我自己的$(document).ready
功能?我知道使用window.onload
会有所不同,因为window.onload
会在加载完所有图像、帧等之后触发。
发布于 2009-04-28 21:59:53
有一个基于标准的替代品,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 );
}
发布于 2012-08-05 02:13:43
穷人的解决方案:
var checkLoad = function() {
document.readyState !== "complete" ? setTimeout(checkLoad, 11) : alert("loaded!");
};
checkLoad();
添加了这个,我想是更好的,自己的作用域,非递归的
(function(){
var tId = setInterval(function() {
if (document.readyState == "complete") onComplete()
}, 11);
function onComplete(){
clearInterval(tId);
alert("loaded!");
};
})()
发布于 2013-12-24 03:14:33
我使用的是:
document.addEventListener("DOMContentLoaded", function(event) {
//Do work
});
注意:这可能只适用于较新的浏览器,特别是这些浏览器:http://caniuse.com/#feat=domcontentloaded
https://stackoverflow.com/questions/799981
复制相似问题