Defer loading of js how?
Asked Answered
A

5

5

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?

Akron answered 19/11, 2013 at 18:53 Comment(2)
Who cares what pageSpeed says, the important question is can the script be deferred, or in other words, is it something unimportant that won't matter if it's loaded after everything else is loaded.Monroemonroy
It's possible doing so would be more effort than it's worth - defer is only compatible with newer browsers, and I think only helps if the script is declared in the <head>. However, if it is moved and the browser doesn't know defer, then it will mess up execution by running too early.Tinker
I
5

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

Insightful answered 19/11, 2013 at 18:55 Comment(0)
P
1

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.

Pindaric answered 19/11, 2013 at 18:56 Comment(1)
I like this option better. any downsides?Akron
S
1

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>

Squishy answered 19/11, 2013 at 18:57 Comment(0)
F
1

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

Feoff answered 3/8, 2014 at 3:3 Comment(0)
E
0

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.

Everrs answered 10/5, 2017 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.