Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 668
Kermit the Frog Avatar asked Nov 19 '13 18:11

Kermit the Frog


People also ask

How do you defer a script load?

Use async or defer # The async and defer attributes tell the browser that it may go on parsing the HTML while loading the script in the background, and then execute the script after it loads. This way, script downloads don't block DOM construction and page rendering.

What do we achieve by deferring the loading of JavaScript?

Deferring loading of JavaScript functions that are not called at startup reduces the initial download size, allowing other resources to be downloaded in parallel, and speeding up execution and rendering time.

How do I stop JavaScript from loading?

Open Chrome DevTools. Press Control+Shift+P or Command+Shift+P (Mac) to open the Command Menu. Start typing javascript , select Disable JavaScript, and then press Enter to run the command. JavaScript is now disabled.


2 Answers

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

like image 111
pilsetnieks Avatar answered Sep 18 '22 12:09

pilsetnieks


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.

like image 31
Satpal Avatar answered Sep 16 '22 12:09

Satpal