Introduction
In web development, the <script> tag is used to add JavaScript to an HTML page. Normally, when the browser finds a <script> tag, it pauses the page loading until the script is downloaded and executed. This can cause a page to load more slowly.
To solve this, HTML provides special attributes, such as async and defer. These attributes change the way JavaScript is loaded and executed. In this article, we will focus on the async attribute.
What Does async Mean?
The word async stands for asynchronous. When you use async with a script:
The script is downloaded at the same time as the HTML page continues loading.
Once the script is fully downloaded, it is executed immediately.
The browser does not wait for the whole HTML page to finish loading before running the script.
This helps make websites faster because scripts are not blocking the page.
Syntax of async
Here is how you use the async attribute:
<script src="script.js" async></script>src="script.js"→ points to the external JavaScript file.async→ tells the browser to download the file without blocking the HTML.
How Does async Work?
When a browser loads a web page with an async script, the process looks like this:
The browser starts reading the HTML page line by line.
When it finds
<script src="file.js" async>, it starts downloadingfile.jsin the background.While the file is downloading, the browser continues reading the HTML and loading the rest of the page.
As soon as the script finishes downloading, the browser pauses the HTML parsing and immediately executes the script.
After running the script, the browser continues loading the remaining HTML.
Example Without async
<html>
<head>
<script src="script1.js"></script>
<script src="script2.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>The browser stops at
script1.js, downloads it, runs it, then moves toscript2.js.Only after both scripts are done, it continues showing the rest of the page.
This makes the page load slower.
Example With async
<html>
<head>
<script src="script1.js" async></script>
<script src="script2.js" async></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>Both scripts download while HTML keeps loading.
The browser executes whichever script finishes downloading first.
The execution order is not guaranteed.
When Should You Use async?
You should use the async attribute when:

Join the conversation! Your thoughts help the community grow.