‘async’ and ‘defer’ on <script>

Rakshith Kakathkar
2 min readJan 23, 2022

--

The most underrated attributes are the ‘async’ and ‘defer’ on the <script> tag in html, sometimes these are used without understanding the use case.

1. <script src=””> HTML is parsed by browser, as soon as <script> is encountered, HTML parsing is stopped and it fetches the script and executes it. After script execution HTML parsing continues.

2. <script async src=””> HTML is parsed by browser, as soon as <script> is encountered, browser fetches the script in the background and once the script is fetched, HTML parsing is paused and script executes. After the script execution, HTML parsing continues.

3. <script defer src=””> HTML is parsed by the browser, as soon as <script> is encountered, browser fetches the script in the background and once the HTML parsing is completed, the script is executed.
Note: ‘defer’ and ‘async’ is skipped if src is not passed to <script>

Pictorial representation of ‘async’ and ‘defer’

When to use what?
a. ‘defer’ attribute is preferred when there are multiple scripts which may be dependent on each other. If ‘async’ is used we might not be having the dependent scripts yet and the code might break.
b. ‘async’ can be used when the scripts are independent of each other. Since they are independent they can execute on their own.

Refer to the image for a pictorial representation of the differences.

Credits Akshay Saini for his clear and simple explanation.
#html #frontenddevelopment

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Rakshith Kakathkar
Rakshith Kakathkar

Written by Rakshith Kakathkar

Hello reader, I am Rakshith Kakathkar a software engineer. I am on a mission to share my knowledge in the simplest way possible!

No responses yet

Write a response