javascript 延迟加载js怎么办?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20079682/
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
Defer loading of js how?
提问by Kermit the Frog
I have the following js script referenced on the bottom of the page:
我在页面底部引用了以下 js 脚本:
<script src="http://example.com/test.js" type="text/javascript"></script>
Google PageSpeed suggestion is to defer the loading of this js. I don't quite understand how to do that or the repercussions. Can someone please explain?
Google PageSpeed 的建议是推迟加载这个 js。我不太明白如何做到这一点或影响。有人可以解释一下吗?
回答by pilsetnieks
Adding the attribute defer
to the <script>
tag should do it. E.g.:
将属性添加defer
到<script>
标签应该这样做。例如:
<script src="http://example.com/test.js" type="text/javascript" defer></script>
The idea is that the script in the file is executed only after the whole page has finished loading, as opposed to the standard way when the script is executed as soon as the browser parses the <script>
tag (which may delay rendering of the code after the <script>
tag.)
这个想法是在整个页面加载完成后才执行文件中的脚本,而不是浏览器解析<script>
标签后立即执行脚本的标准方式(这可能会延迟<script>
标签后的代码渲染.)
回答by gat
Here's what you'd want to do: http://davidwalsh.name/html5-async
这是你想要做的:http: //davidwalsh.name/html5-async
<script async src="siteScript.js" onload="myInit()"></script>
<script async src="siteScript.js" onload="myInit()"></script>
or
或者
<script defer src="siteScript.js" onload="myInit()"></script>
<script defer src="siteScript.js" onload="myInit()"></script>
回答by maljukan
None of those methods are really guaranteed to be executed. Check this great article on how to make sure that external javascript executions are really deffered.
feedthebot deffer execute javascript
这些方法都不能真正保证被执行。查看这篇很棒的文章,了解如何确保真正延迟外部 javascript 执行。
feedthebot defer 执行javascript
written by Patrick Sexton
帕特里克·塞克斯顿撰写
回答by Shrikanth K M
asyncmight not be good option when there are dependencies from one js to another js. For eg . file1.js depends on file2.js , and file1.js loads first, starts executes but fails and throws an error due to some dependency in file2.js which is not loaded yet.
当从一个 js 到另一个 js 存在依赖关系时,异步可能不是一个好的选择。例如。file1.js 依赖于 file2.js ,并且 file1.js 首先加载,开始执行但由于尚未加载的 file2.js 中的某些依赖项而失败并引发错误。
回答by Satpal
You can use async
attribute
您可以使用async
属性
<script src="http://example.com/test.js" type="text/javascript" async></script>
Note:
笔记:
The async attribute is supported in Internet Explorer 10, Firefox, Opera, Chrome, and Safari.
Internet Explorer 10、Firefox、Opera、Chrome 和 Safari 支持 async 属性。