Defer loading of js how?

你离开我真会死。 提交于 2021-01-27 05:57:23

问题


I have the following js script referenced on the bottom of the page:

<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?


回答1:


Adding the attribute defer to the <script> tag should do it. E.g.:

<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.)




回答2:


Here's what you'd want to do: http://davidwalsh.name/html5-async

<script async src="siteScript.js" onload="myInit()"></script>

or

<script defer src="siteScript.js" onload="myInit()"></script>




回答3:


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

written by Patrick Sexton




回答4:


You can use async attribute

<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.




回答5:


async might 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.



来源:https://stackoverflow.com/questions/20079682/defer-loading-of-js-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!