Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html

How to use the async attribute in the HTML <script> tag

Abdul Muizz

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In this Answer, we'll learn the use of async attribute in HTML <script> tag. This is a booleanA boolean variable has only two values. In our case, it is either true or false. attribute that ensures that the JavaScript for a particular web page runs asynchronously as the browser parses it.

Note: The async attribute can only be used when JavaScript is linked externally to the HTML file. This is done using the src attribute of <script> tag.

Syntax

<script async></script>

Example

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css"/>
    </head>
    <body>
        <div id="content">
            <img class="educativelogo" src='logoMarkv2.png'/>
            <h3 class="heading">Welcome to Educative Answers!</h3>
        </div>
        <script src="script.js" async></script>
    </body>
</html>

Explanation

Below is the explanation for the code in index.html:

  • Line 4: This line contains a <link> tag that links to styles.css . This file contains the necessary styling for our page.
  • Lines 7–10: In this piece of code, we have a parent <div> tag that encapsulates the <img> tag and the <h3> tag. These tags render the output as seen in the code widget above.
  • Line 11: We use the <script> tag and the src attribute to link to the external 'script.js' file in our project directory. We also specify the async attribute so that it loads the JavaScript code as the web page is displayed.

Below is the explanation for the code in script.js:

  • Line 1: This line of code contains JavaScript alert(), which displays the message to the user to demonstrate the functionality of the async attribute.

Note: More details on JavaScript alert() can be found in this Answer.

RELATED TAGS

html

CONTRIBUTOR

Abdul Muizz
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring