Using HTML5 async Attribute to Run JavaScript Asynchronously

← PrevNext →

A few months back I have written an article on How to register and call a JavaScript function using code behind procedures. At the end of that article (in the conclusion part), I have added a paragraph explaining how to asynchronously load a .js file using HTML5 async attribute.

The HTML5 async attribute will ensure that the script runs asynchronously during the rendering of the web page. In simple terms it means it will execute the script in the .js file asynchronously, while the HTML page is also loaded. Why is this important? I have explained this in the later part of this article.

General Syntax of async attribute

<script async>

The HTML5 async attribute is a Boolean attribute, that is, you can assign it as true or false. Therefore, if you want to load an external .js file asynchronously, then this is how you write it.

<script async="true" src="file.js">

Or

<script async src="file.js">

I have mentioned "external .js file", which means, the script that is executed is from an external file and is added to the HTML page, using the src attribute. If in any case, you have written a script in the HTML page (also called inline script), then you need not use the async attribute at all.

Why use async attribute?

It is a common practice to include a .js file at the top of the HTML page, inside the <head> tag. When the browser loads the page and it reads the scripts inside the .js file, it will first execute the scripts (functions, events, anything) and then loads the rest of the page. This may increase the page load time, since it is busy executing the scripts.

Now technically, executing the scripts before the page is loaded will make no sense. Because, the elements, its attributes etc, on which the scripts are written, are not yet loaded.

Therefore, it is advisable to use the async attribute inside the <script> tag that has a src attribute. Remember, if you have added the <script> tag with the .js src on the top of HTML page, above the fold, then don’t forget to add the async attribute.

<head>
    <script src="file.js" async> </script>
</head>

Browser Support:
Chrome 39.0 - Yes | FireFox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - Yes

Here's an Example

<body>
    <h2>Clock script loaded asynchronously from an external .js file.</h2>

    <script src="https://www.encodedna.com/library/clock.js" async onload="digiclock()"></script>
    <div id="clock" style="float:left;margin-right:5px;"></div>
    <span id="second"></span>
    <span id="hour"></span>
</body>
Try it

← PreviousNext →