Async And Defer Scripts

Photo by Jess Bailey on Unsplash

Async And Defer Scripts

ยท

2 min read

Introduction

Async and Defer are boolean attributes used with script tags in HTML to load scripts efficiently.

Whenever a browser loads a webpage two significant things happen behind the scenes:

  • HTML Parsing

  • Script Loading

Further, two things in script loading are:

  • Script Fething: Fething scripts from the network;

  • Script Execution: Once the script is fetched, it is ready to get executed

Loading Scripts Without Async And Defer

<script src="index.js"></script>

The Brower starts HTML parsing, and as soon as it encounters a script tag, it starts fetching that script from the network when fetching is completed it executes the script. note that during script fetching and execution, the HTML parsing gets blocked, and it continues only after the execution of the script gets completed.

Loading Script With Async Attribute

<script async src="index.js"></script>

By using the async attribute in the script tag, the browser fetches the script asynchronously with HTML parsing. and when the script is ready to be executed, It blocks the HTML parsing and executes the script. The HTML parsing continues after the execution of the script.

NOTE: If there is more than one script in your code then the order of execution of scripts is not certain.

Loading Script With Defer Attribute

<script defer src="index.js"></script>

By using the defer attribute in the script tag, the browser will fetch the script asynchronously with the HTML parsing, but this will never block the HTML parsing, the script will get executed only after the completion of the HTML parsing. Note the HTML parsing gets never blocked when we are using defer attribute.

Note: If there is more than one script tag in your code then they are executed according to their order in your code.

THANKS FOR READING!โค

If you have any queries related to web development ask me in the comment section.

About Me
I'm a Web Development Enthusiast, I try to make web development concepts easy through my articles. So if you are a beginner, who is starting a carrier in web development then make sure to follow me here. WE WILL GROW TOGETHER AND WILL BECOME GREAT WEB DEVELOPERS ๐Ÿ˜Š
ย