Hello, my name is: Amy

What did you learn yesterday/this week?

This is something that is incredibly simple, but has potential to be a big deal. Ready for it? It's just that with HTML5 you can now add an async attribute to a <script> tag so that it will be non blocking. Yeah, wow.

Traditionally what happens when the browser loads your site is that it will render everything in the HTML (content/css/images) simultaneously; BUT, when it gets to a script it stops everything its doing and loads the entire script before proceeding.

Modern browsers now will still scan through the rest of the content and download any external content it may need, but content rendering is still blocked and your users will be looking at a blank screen. (Users hate looking at blank screens.)

Traditionally this is why we put our non-load-critical scripts at the bottom of web pages, so the content will get loaded first before the browser concentrates on executing scripts.

But for a load critical script, if you do absolutely need it at the top you're able to add the async attribute now and the browser will simultaneously process the content of the page as well as your script. Cool!

Just add it like so: <script src="scripts.js" async></script>.

A few things to note:

  • If your script relies on knowing what is in the HTML you will definitely still want to include the scripts at the bottom or inside an onload listener. Using async doesn't change the fact that if all the HTML isn't loaded when your script runs then your script doesn't know about it.

  • Loading your script asynchronously means that you might not have control over exactly when those scripts execute. If you're going to use async you'll want to make sure they can operate independently.

Further Reading

Jake Archibald wrote a fantastic article on script loading that I'll need to reference should I need to do something fancy with script loading. Briefly reading through this article he suggests a few ways that you can load scripts at the head that will both be non-blocking to content as well as execute in order. I'll leave it to him to explain all that.