Last Updated: February 25, 2016
·
2.141K
· 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

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

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.

Examples

<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!


http://www.nczonline.net/blog/2010/08/10/what-is-a-non-blocking-script
http://www.stevesouders.com/blog/2009/04/27/loading-scripts-without-blocking
http://css-tricks.com/thinking-async
https://developer.mozilla.org/en/HTML/Element/script