在某些情况下,由于下载速度或其他异步问题,即使我在包含 jquery.js 之后放置 $(document).ready()
,有时我也会收到提示$
是未定义
。巴拉巴拉巴拉。
我不想这样做:
setTimeout(function() {$(document).ready()... }, 1000);
这看起来很蹩脚。
那么,有没有一种聪明的方法或正确的方法或好的方法来确保 document.ready 真的准备好被调用? :)
最佳答案
我相信这实际上是不可能的,(事实上 $
将是 undefined
),文档头同步加载意味着每一行在下一行之前完全加载
这里有一个视频,其中进行了精确的测试测试,看来我是正确的
视频:http://www.bennadel.com/blog/1915-How-Javascript-Loading-And-Blocking-Works-By-Default.htm
您是否正确加载文件,例如
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<script type="text/javascript" src="...."></script>
<script type="text/javascript" src="...."></script>
<script type="text/javascript" src="...."></script>
<script type="text/javascript" src="...."></script>
<script type="text/javascript">
jQuery.ready(function(){
//This is executed once all 4 above have been loaded
});
</script>
<script type="text/javascript" src="...."></script>
<script type="text/javascript" src="...."></script>
<!-- The above to scripts are loaded in order after the jquery function has run. -->
</head>
</html>
ready
jQuery 的方法 only 在洞文档加载后被触发,直到 DOM 看到最终的结束标签,通常是 </html>
[需要引用]
虽然说不可能,但在 IE8 或更低版本中可能是可能的,原因是 IE 可能是有史以来最差的浏览器,但他们说 IE9 已经彻底改版了,应该满足于喜欢Google、Apple、Mozilla 等
如果您使用多个库或覆盖 $
变量,您可以将其返回到锁定范围内,如下所示:
(function($){
$.ready(function(){
//Do your jQuery here !
});
})(jQuery)
关于jquery - 如何确保 $(document).ready 在 jQuery.js 可用后运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5396018/