How to “Really” defer loading of JavaScript?

The websites nowadays uses a LOT of JavaScript. However, defer loading of JavaScript is actually a big headache as there’s really, really many ways to do it.┬áSomeone may call you “just use defer” or “just use async” or even “just put it on the bottom of the page”.

Actually, none of these methods really solve the problem that allows a page to be fully loaded before loading scripts. None of these methods actually gets passed of the “Defer loading of scripts” if you’re trying to test it with Google PageSpeed.

The right way

In here, I’ll show you the right method of defer loading JavaScript that Google also recommends.

Beware: You should put this just before </body> (near the end of an HTML file)

What it really does is to load the JavaScript after the page has been fully load i.e. The onload event has been triggered.

Why the other methods don’t work?

The methods of inlining, placing scripts at the bottom, using “defer” or using “async” all do not accomplish the goal of letting the page load first then loading JS and they certainly do not work universally and cross browser.

Speed

defer-methods

You can see that with this method, the page load speed has a very great increase. As the other methods don’t match the goal of loading JavaScript only after the page has finished loading, it can be very slow especially for large JS files.

Final word

Our first priority is to deliver the content to the user as soon as possible. If a user waits because there’s some JavaScripts still loading that doesn’t affect the content, the user may leave because of the long waiting. (The average wait time for a visitor is around 2 – 3 seconds) Therefore, you should remember the right method of deferring JavaScript loading.

Published by

Licson Lee

Hi! I'm Licson. I'm a student who loves programming.

3 thoughts on “How to “Really” defer loading of JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *