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
The HTML5 async attribute is a Boolean attribute, that is, you can assign it as true or false. Therefore, if you want to load the external .js file asynchronously, then this is how you write it.
<script async="true" src="file.js">
<script async src="file.js">
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>
Chrome 39.0 - Yes | FireFox 34.0 - Yes | Internet Explorer 10 - Yes | Safari - Yes
Here's an Example
<html> <head> </head> <body> <p>Clock script loaded asynchronously from an external .js file.</p> <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> </html>