如何防止 JavaScript HTML 阻塞
如何防止 JavaScript 阻止其他 JavaScript 开始下载?
我的网站上有以下内容:
<html>
<body>
....
<script type="text/javascript" src="http://example.com/ex.js"></script>
<script type="text/javascript" src="http://google.com/google-maps.js"></script>
</body>
</html>
当我使用 YSlow Firefox 插件时,我可以从网络流量选项卡中看到 google.com/google-maps.js
JavaScript 无法启动下载直到 ex.js
完成下载。
问题:如何让 ex.js
和 google-maps.js
立即开始并行下载?
How do I prevent JavaScript from blocking other JavaScript's from starting to download?
I have the following on my web site:
<html>
<body>
....
<script type="text/javascript" src="http://example.com/ex.js"></script>
<script type="text/javascript" src="http://google.com/google-maps.js"></script>
</body>
</html>
When I use the YSlow Firefox add-on, I can see from the network traffic tab that the google.com/google-maps.js
JavaScript won't start downloading until ex.js
has finishes downloading.
Question: How can I have both ex.js
and google-maps.js
begin downloading immediately and in parallel?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
元素的 < code>async 或
defer
属性:defer
。async
。 (不 IE 支持!)defer
是您的最佳选择。脚本将并行下载并同步执行(按顺序)。它也比异步得到更好的支持和更可预测。 (另请参阅这个对async
/defer<的非常详细的分析/代码>
。)
Use the
<script>
element'sasync
ordefer
attribute:defer
is supported by IE4+, Firefox 3.5+, Chrome 2+, and Safari 4+.async
is supported by Firefox 3.6+, Chrome 7+, and Safari 5+. (No IE support!)defer
is your best choice. Scripts will download in parallel and execute synchronously (in order). It's also better supported and more predictable thanasync
. (See also this very detailed analysis ofasync
/defer
.)它很丑陋,但您可以通过使用 javascript 注入 DOM 元素来并行下载脚本。
请查看此博文了解工作示例。
It's ugly, but you can get scripts to download in parallel by injecting the DOM elements ... using javascript.
Check out this blog post for a working example.
这对于 HTML 中的内联脚本来说是正常的。您可以使用以下代码动态添加脚本:
但是,这可能会导致意外结果 - 它们可能无法以正确的顺序下载和解析,如果脚本 2 引用脚本 1 中的变量或函数,这一点很重要
。在脚本加载之前加载 HTML,保持它们的顺序并将它们放在 HTML 文件的底部,而不是放在 head 标记中。这将在下载和解析脚本之前加载页面。请参阅http://developer.yahoo.net/blog/archives/2007 /07/high_performac_5.html。
This is normal for inline scripts in HTML. You could add the scripts dynamically using the following code:
This could cause unexpected results, however - they may not be downloaded and parsed in the correct order, which is important if script 2 references variables or functions from script 1.
If you just want your HTML to load before the scripts load, keep them sequential and put them at the bottom of your HTML file, not in the head tag. This will load the page before downloading and parsing the script. See http://developer.yahoo.net/blog/archives/2007/07/high_performanc_5.html.
JavaScript 文件将始终按照指定的顺序下载。
The JavaScript files will always download in the order they are specified.