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
anddefer
attributes are boolean attributes that indicate how the script should be executed. Thedefer
andasync
attributes must not be specified if thesrc
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 theasync
attribute is not present but thedefer
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!
Comments