React Learning Path - Day 2

Async vs Defer

<script src="" />
Usually, we place the script tag at the bottom of the body tag so that HTML parsing is done before executing the script because if the script tag is encountered before then the HTML DOM is built then won't complete the later HTML parsing after the script tag until the script fetching and execution is completed. This sometimes can cause an issue when the fetch and execution time of the script tag is more hence we use two script tag attributes defer or async.

async

<script async src="" />

In the above diagram, we can see that in async mode the fetching is done in the background without stopping the HTML parsing and once fetching is complete HTML parsing is put on hold then script execution starts. Here HTML parsing will resume after the completion of script execution.

defer

<script defer src="" />

Similar to async, in the above diagram we can see that in defer mode the fetching happens in the background and execution of the script happens after the completion of the HTML parsing. Hence HTML parsing is not interfered or put on hold for script execution even after fetching of the script is complete in the background.
In the above diagram, we can see the deferred mode as well for better understanding.

When to use defer / async?
When we need that the script should be executed sequentially then we use defer because when we use the async attribute the script are might run in any order i.e. the order of the execution of the script does not remain constant.
When we use the external script is used we generally use async.