HTML5 Tutorial – Asynchronous Script Execution

10063_580983808600819_401360548_nFor pages using process-intensive scripts, you can get quicker page loading with the async attribute for the script element.

This enables the associated script to load and execute asynchronously with respect to the rest of the page. That is, the script loads and executes in the background while the page continues to be parsed.

Without the async (or defer) attribute, a script can block other page content from loading.

If you write your JavaScript effectively, you’ll use the async attribute to 90% of your SCRIPT elements.


<head>
<title>My Title</title>
<script async src="widgets.js"></script>
</head>

WebKit, Chrome 11+, Safari 5+, Firefox 4+, IE 10 have implemented HTML5’s async attribute for script element.  It is part of the HTML5 script specification, that is part of HTML5: A vocabulary and associated APIs for HTML and XHTML.

Async and Defer

The async and defer attributes are boolean attributes that indicate how the script should be executed. The defer and async attributes must not be specified if the src 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 the async attribute is not present but the defer 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.

The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.

Best Practice

Make sure your browser supports this new async feature. To see if your browser can handle by you can use the following feature detection:


function testSupport() {
var script = document.createElement("script");
if(typeof script.async == "undefined") {
//not supported
} else if(script.async != true) {
//Script execution order not supported
}
}

Demonstration

For a hands-on demonstration of asynchronous script execution, see HTML5 Async Scripts on the IE Test Drive.

References