Middle
What is the difference between <script>, <script async>, and <script defer> tags?
sobes.tech AI
Answer from AI
The standard <script> stops HTML parsing, loads the script, and executes it, then parsing continues.
<script async> loads the script asynchronously, while HTML parsing continues. The script executes immediately after loading. The execution order is not guaranteed.
<script defer> loads the script asynchronously, while HTML parsing continues. The script executes only after HTML parsing is complete, but before the DOMContentLoaded event fires. The order of execution of defer scripts is preserved according to their appearance in HTML.
Comparison table:
| Attribute | HTML parsing during script loading | Script execution | Preservation of execution order |
|---|---|---|---|
| None | Pauses | Immediately after loading | Yes |
async |
Continues | Immediately after loading (may interrupt parsing) | No |
defer |
Continues | After HTML parsing is complete | Yes |
Example:
<!-- Normal script - blocks parsing -->
<script src="script1.js"></script>
<!-- Asynchronous script - does not block parsing, executes immediately after loading -->
<script src="script2.js" async></script>
<!-- Deferred script - does not block parsing, executes after HTML parsing -->
<script src="script3.js" defer></script>
<script src="script4.js" defer></script> <!-- Will execute after script3.js -->