Last Updated: February 25, 2016
· grayghostvisuals

Non-Blocking Scripts

HTML5 allows authors to easily disallow scripts from blocking page rendering by implementing the 'async' attribute. This boolean attribute indicates that the browser should, if possible, execute the script asynchronously. This is important because JavaScript is fundamentally single-threaded, meaning only one operation can be performed at a time. This will soon change.

The Old Way

  var resource = document.createElement('script'); 
  resource.src = "//path/to/resource.js";
  var script = document.getElementsByTagName('script')[0];
  script.parentNode.insertBefore(resource, script);

The New Way

Simply add the async attribute like so and viola!
<script src="path/to/file.js" async></script></code></pre>

When to add 'async' attribute

So when is it cool to use the async attribute on <script></code> tags?

If your Javascript doesn't modify the DOM you can add the async or defer attribute or both to your <script></code>  elements to prevent blocking.


<script src="path/to/file.js" async></script>
<script src="path/to/file.js" defer></script>
<script src="path/to/file.js" async defer></script></code></pre>

Cross Browser Advice

Include Style Sheets before scripts before any js blocks
Place scripts at the end of the HTML just before body tag
Force scripts to download asynchronously. Search "loading scripts without blocking"

Hot Links!