简体   繁体   中英

Defer loading of js how?

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?

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

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

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

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>

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM