In this Answer, we'll learn the use of async
attribute in HTML <script>
tag. This is a boolean 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 thesrc
attribute of<script>
tag.
<script async></script>
<!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>
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.
Free Resources