Do you know about these essential concepts for JS Interviews? if not let's dive deep into it
We will try to explain in it straightforward terms and not so fancy and overwhelming stuff
What are async and defer?
Async and defer are attributes that are used along with script tags to use the external scripts efficiently on our webpage
We will see 3 scenarios here
Using normal script tag
Using async attribute with the script tag
Using defer attribute with the script tag
What happens when we load a webpage?
When we load a webpage there are two major things happening - one is HTML Parsing second is the loading of the scripts, now loading of the scripts contains two parts - fetching the script from the network and executing that script line by line
Normal Script Loading
Whenever we load a webpage HTML Parsing starts and when the execution comes to the script, the parsing stops and the script starts executing - it fetches the script from the network and starts executing line by line, and when this finishes, then only the remaining HTML Parsing continues
Script Loading with Async
In the case of async, the scripts are fetched from the network in parallel to HTML Parsing and when they are available in the browser then only the scripts start executing, and then only HTML Parsing is blocked at that period of time only ( when scripts are being executed after fetching )
Script Loading with Defer
In the case of defer also the scripts are fetched in parallel to HTML Parsing but they are executed only after the whole HTML Parsing finishes then only the scripts would start executing
As we saw how they are used and what they do, but now the important question is when to use what?
Use Cases
The async attribute doesn’t guarantee the order of execution of the scripts but defer does
For example, if we have a situation where multiple scripts are dependent on each other then using an async attribute is not a good choice as you don’t know which script would start executing in a particular order and it may break your code, use defer in this case
We may use async when scripts are not dependent on one another if want to use it with any external scripts such as google analytics and they are independent of each other, otherwise, we should prefer to use defer attribute
That's a wrap I hope you liked the blog, do share it too!