Where developers come to connect, share, build and be inspired.


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>

When to add 'async' attribute

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

If your Javascript doesn't modify the DOM you can add the async or defer attribute or both to your <script> 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>

Cross Browser Advice

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

Hot Links!

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


Add a comment