Table of Contents
- How HTML displayed on browser
- Script Tag
- Async attribute
- Defer attribute
- Difference beetween Async and Defer
- Use cases
How HTML displayed on browser
First, browser will download resources and parse HTML to display. HTML is parsed as soon as resources are loaded
Script Tag
To load a javascript file, we use script tag
<script src="/path/to/script.js"></script>
👇️Below is loading process:
✍️ Explain:
First, HTML code will be parsed until reach script tag, script will be downloaded. After that, script will be executed. After executing the script, continue to execute the DOM analysis.
⛔️ Drawback:
This case above results in a bad user experience because the user cannot interact with the page while the script is being downloaded.
To avoid that, HTML5 provides two attributes: async and defer
Async attribute
🟢 Declaration syntax
<script src="/path/to/script.js" defer></script>
👇️Below is loading process when using defer attribute:
✍️ Explain:
Downloading script run parallel with parsing the document. After script is downloaded, parsing HTML is paused and script will be executed. After script is executed successfully, parsing HTML is continue.
Defer attribute
🟢 Declaration syntax
<script src="/path/to/script.js" async></script>
👇️Below is loading process when using async attribute:
✍️ Explain:
The process is quite similar to above process. Downloading script run parallel with parsing the document. After parsing HTML is compeleted, script will be executed.
Difference beetween Async and Defer
- The first difference is loading process as mentioned above.
- When using async, scripts may not be executed in order because scripts are executed as soon as they are completely downloaded. On the other hand, the scripts used defer guarantee the order of execution.
Use cases
1️⃣ Use cases of defer
- Gets loaded as soon as possible — so it reduces load times.
- Guarantee scripts order
- Your script requires the DOM
2️⃣ Use case of async
- Your script dont need the DOM
- The script doesn’t depend on other scripts (ex: Google Analytics)
- Loading script in the middle
Example:
<div class="middle">
<script async src="./script.js"></script>
</div>
Because the DOM is already present, the script can be executed without problems.