HTML - async Attribute



HTML async attribute is a Boolean attribute that is used to specify the script to execute as soon as it is loaded.

It is similar to defer attribute in an HTML. As we know that the async attribute is a Boolean attribute that returns true with JavaScript if present within the <script> element, otherwise it will return false.

The difference between async and defer is that the async attribute allows the script to run as soon as it is loaded, without blocking the other elements on the web page. On the other hand, the defer attribute allows the script to execute only after the page has finished loading.

Syntax

<script async></script>

Applies On

Below listed element allow using of the HTML async attribute.

Element Description
<script> HTML <script> tag is used to add javascript code to HTML document.

Examples of HTML async Attribute

Following codes demonstrate the usages of async attribute.

Async attribute with script Tag

When we execute the below script, it will generate an output displaying the alert as soon as the page load. when the user clicks the ok it will displays a text.

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML 'async' attribute</title>
</head>

<body>
   <!--HTML 'async' attribute-->
   <h3>Example of the HTML 'async' attribute</h3>
   <p>This is demo of the HTML 'async' attribute.</p>
   <!--use within the 'script' element-->
   <script src="index.js" async></script>
</body>

</html>

index.js

alert("Alert message...")

Check async is present in current script

Considering the another scenario, where we are going to run the script to check whether the attribute present in the script tag or not.

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML 'async' attribute</title>
   <style>
      button {
         padding: 10px;
         width: 100px;
         cursor: pointer;
         background-color: blueviolet;
         color: white;
      }
   </style>
</head>

<body>
   <!--HTML 'async' attribute-->
   <h3>Example of the HTML 'async' attribute</h3>
   <p>This is demo of the HTML 'async' attribute.</p>
   <p>
      Click on the below button to check the 'async' 
      attribute is present within the 'script' element or not.
   </p>
   <button onclick="func()">Check</button>
   <!--use within the 'script' element-->
   <script src="index.js" id="demo" async></script>
   <script>
      function func() {
         let value = document.querySelector("#demo").async;
         alert("Is 'async' is present or not? " + value);
      }
   </script>
</body>

</html>

Supported Browsers

Attribute Chrome Edge Firefox Safari Opera
async Yes Yes 10.0 Yes 3.6 Yes Yes
html_attributes_reference.htm
Advertisements