如何确保 $(document).ready 在 jQuery.js 可用后运行?
在某些情况下,由于下载速度或其他异步问题,即使我在包含 jquery.js 之后放置 $(document).ready()
,有时我也会收到关于 的抱怨$
是未定义
。巴拉巴拉巴拉。
我不想那样做:
setTimeout(function() {$(document).ready()... }, 1000);
这看起来很蹩脚。
那么,是否有一种聪明的方法或正确的方法或好的方法来确保 document.ready 真正准备好被调用? :)
In some cases, because of download speed or other async issue, even I put $(document).ready()
after including jquery.js, from time to time, I will get complains about $
is undefined
. blah blah blah.
I don't want to do that:
setTimeout(function() {$(document).ready()... }, 1000);
that seems very lame.
so, is there a smart way or proper way or good way to ensure document.ready is really ready to be called? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信这实际上是不可能的,(事实上,
$
将是未定义
),文档头同步加载意味着每行之前都已完全加载下一行这里有一个视频,其中这个精确的测试被放入测试中,看来我是正确的
视频:http://www.bennadel.com /blog/1915-How-Javascript-Loading-And-Blocking-Works-By-Default.htm
您是否正确加载文件,例如
jQuery 的
ready
方法only 一旦洞文档被加载,就会被触发,直到 DOM 看到最终的结束标签,通常是[需要引用 】
虽说不可能,但在 IE8 或更低版本中可能是可能的,原因是 IE 可能是有史以来最差的浏览器,但他们说 IE9 已经彻底改版了,应该满足于 Google 这样的浏览器、Apple、Mozilla 等
如果您使用多个库或覆盖
$
变量,您可以将其返回到锁定范围内,如下所示:I believe that is actually impossible, (the fact that
$
would beundefined
), the document head loads synchronously meaning each line is fully loaded before the next lineThere is a video here where this exact test is put to the test and it seems I was correct
Video: http://www.bennadel.com/blog/1915-How-Javascript-Loading-And-Blocking-Works-By-Default.htm
are you loading the files correctly such as
the
ready
method of jQuery only gets fired once the hole document has been loaded, until the DOM see's the final ending tag, usually</html>
[citation needed]having said that its impossible, it may be possible in IE8 or lower, the reason for this is because IE is possibly the worst browser ever made, but they have said that IE9 has totally had a overhaul and should content with the likes of Google, Apple, Mozilla etc
If your using multiple libraries or your overwriting the
$
variable you can get it bac inside a locked scope like so:您可以通过以下方式检查 jQuery 是否已加载。
您不必这样做。最好将所有 JavaScript 包含在 HTML 末尾、
之前,其中 jQuery 优先。这是yahoo推荐的方法。您可以在 http://developer.yahoo.com/performance/rules.html。这不会减慢您的页面加载速度,也不会给您带来未定义 jQuery 的问题。
You can check if jQuery is loaded by doing.
You do not have to do this. It is best to include all your JavaScript at the end of your HTML and before
</body>
, jQuery being first. This is the recommended method by yahoo. You can read more at http://developer.yahoo.com/performance/rules.html. This will not slow down your page load and will not give you issues with undefined jQuery.Denis 提供了一个很好的解决方案的链接。我现在正在使用它。
JavaScript - 如何确保 jQuery 已加载?
请参阅链接中的答案和解释。
解决办法是:
Denis has provided a link with a good solution. I am using it now.
JavaScript - How do I make sure a jQuery is loaded?
See the answer and explanation in the link.
the solution is: