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?
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.
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.
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.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With