HTML - async Attribute



The 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

Following is the syntax for HTML async attribute −

<script async></script>

Example

In the following example, we are using the HTML ‘async’ attribute with the <script> tag.

<!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...")

When we execute the above 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.

Example

Considering the another scenario, where we are going to run the scrip 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>

On executing the above script, the output window will pop up displaying the alert as soon as the page. when the user clicks ok it will displays text along with a click button.

html_attributes_reference.htm
Advertisements