Javascript 如果 jQuery 不可用,有没有办法检查 document.ready() ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5706757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to check document.ready() if jQuery is not available?
提问by bobobobo
Possible Duplicate:
$(document).ready equivalent without jQuery
I know you can use the window.onload event to make functions run, but is there a way for a script to query if the document is ready or not?
我知道您可以使用 window.onload 事件来运行函数,但是有没有办法让脚本查询文档是否准备就绪?
Something like
就像是
function update()
{
if( !document.ready() ) // don't do unless document loaded
return ;
}
window.setInterval( 'update();', 100 ) ;
Cannot change the <body> element, and no jQuery/other libraries.
不能更改 <body> 元素,也不能更改 jQuery/其他库。
回答by ?ime Vidas
Here you go:
干得好:
var tid = setInterval( function () {
if ( document.readyState !== 'complete' ) return;
clearInterval( tid );
// do your work
}, 100 );
Read about the document.readyState
property here. I am not sure if all current browsers implement it.
回答by James Kyburz
Checkout https://github.com/jakobmattsson/onDomReady
结帐https://github.com/jakobmattsson/onDomReady
It's more complicated than a few lines! - If you want multiple browser compliance.
比几行还复杂!- 如果您想要多个浏览器合规性。
回答by Juggernogger93
This code will work in all browsers
此代码适用于所有浏览器
if(window.attachEvent()){
window.attachEvent("onload",load);
}else{
window.addEventListener("load",load,true);
}
function load(){
//Code to execute when the document is loaded.
}