Asynchronously Load Javascript Files

When loading external javascript files, they will block the rendering of the page, although the slowdown may be barely noticeable if it’s a small script, keep in mind that the bigger the script the longer the delay.
Also keep in mind that you may have many external scripts that you want to load.
Although the scripts will download in parallel (The number of concurrent connections per domain varies between browsers), each one will be executed synchronously, 1 at a time, with each one independently blocking the rendering of your page.

So how can we asynchronously load javascript?

Use The async Attribute

HTML5 introduced the async attribute.
It’s very simple to use, all you have to do is add “async” to your script tag, and you’re done.
Your external script will now execute asynchronously whenever it finished downloading.

Example:
async attribute example

When To Use The async Attribute?

Whenever you have independent external scripts to execute in no particular order, use the async attribute.
For example, if you’ve got an external script which does something non-critical to the function of the page (Such as style manipulation, pop-ups, animations etc), it doesn’t need to block the rendering of the page, it can execute later.

How To Execute The Scripts In Order:

Due to the way the async attribute works (The scripts execute whenever they’ve finished downloading), you’ll be unable to determine the order in which the scripts execute.
To resolve this problem, you can use the defer attribute instead.

The defer attribute behaves exactly the same as the async attribute, except that it will wait until the page has loaded and then it will execute all of the scripts marked with defer, but in the order they were declared in the page.
The defer attribute is the equivalent of putting your external script tags at the bottom of your page, with the exception of the download of the scripts beginning as soon as the parser reaches those tags.

You have the freedom to keep your tags in the head of the document, without fear of them blocking page rendering and be sure of the order the scripts will execute in.

If you enjoyed this article, please consider giving it a +1

Tags: javascript, jquery, asynchronous, async, defer, html5

Published: 5/5/2014 7:46:06 PM
By: Stephen Warren