Quick Win: JavaScript async

A while back when Brandon was working on making Gauges faster, we got in a discussion about adding defer to your script tags. I pointed out that html5 actually defines another attribute: async. That’s what Gauges uses today.

What does it do and why are they using it? From the html5 spec (emphasis mine):

The async and defer attributes are boolean attributes that indicate how the script should be executed. The defer and async attributes must not be specified if the src attribute is not present.

There are three possible modes that can be selected using these attributes. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.

Excellent! This means we can tell (modern and future browsers) to do something asynchronously right inline:

</code>

or if html5’s boolean attribute style scares you:

</code>

With that, the code will immediately begin loading while the rest of your page continues loading. No more blocking!

Dave Walsh has a good summary of async where he comments:

The truth is that if you write your JavaScript effectively, you'll use the async attribute to 90% of your SCRIPT elements.

We already use jQuery to asynchronously load scripts, but that’s no reason not to use async too. Try it out!

Photo of Daniel Morrison

Daniel founded Collective Idea in 2005 to put a name to his growing and already full-time freelance work. He works hard writing code, teaching, and mentoring.

Comments

Add a Comment

Hmm...that didn't work.

Something went wrong while adding your comment. If you don't mind, please try submitting it again.

Comment Added!

Your comment has been added to this post. Please refresh this page to view it.

Optional. If added, we will display a link to the website in your comment.
Optional. Never shared or displayed in your comment.