如果第三方 javascript 文件挂起并需要一段时间才能加载,将会
jQuery(document).ready(function() {})
在调用之前必须等待加载吗?
最佳答案
是的,必须等待。
特别是,您不能依赖 jQuery(document).ready()
在其他脚本有机会执行之前触发。
ready
绑定(bind)到 DOMContentReady、readystatechanged 或 onload(以可用者为准)。
文档指出“在大多数情况下,一旦 DOM 层次结构完全构建完毕,脚本就可以运行”。请注意,唯一的保证是当此事件触发时 DOM 已准备就绪。 它不能向您保证任何其他事情 - 因为它不能。
例如,这在 IE、Firefox 或 Chromium 中不起作用,brilliant.js 始终在 ready()
处理程序之前调用无论你如何打乱脚本标签,都有机会执行:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js" charset="utf-8" type="text/javascript" ></script>
</head>
<body>
<script type="text/javascript" >
// <![CDATA[
alert("attaching event");
$(document).ready(function () { alert("fired"); });
// ]]>
</script>
<script type="text/javascript" src="brilliant.js" ></script>
</body>
</html>
仅供引用,这是 jquery-1.4.2 中的相关代码:
bindReady: function() {
if ( readyBound ) {
return;
}
readyBound = true;
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
return jQuery.ready();
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", 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", DOMContentLoaded);
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
关于jquery - jQuery(document).ready 多久会被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2397534/