<script> tag that affect how JavaScript loads and executes:
When a browser loads an HTML page, it processes (parses) the HTML code sequentially. When encountering a <script> tag, by default the browser:
This can significantly slow down page rendering, especially if scripts are large or loaded from a slow server.
<script async src="script.js"></script><script defer src="script.js"></script>DOMContentLoaded event| Characteristic | Regular Script | async | defer |
|---|---|---|---|
| Blocks HTML parsing during download | Yes | No | No |
| Blocks HTML parsing during execution | Yes | Yes | No |
| Execution order guaranteed | Yes | No | Yes |
| Waits for DOM before execution | No | No | Yes |
| When it executes | Immediately | After loading | After HTML parsing |
<!-- Analytics: doesn't depend on DOM, order doesn't matter -->
<script async src="analytics.js"></script>
<!-- UI library: needs DOM and order matters -->
<script defer src="ui-framework.js"></script>
<script defer src="app.js"></script>async: for independent scripts that don’t need the DOM or other scripts
defer: for scripts that need the fully built DOM or depend on other scripts
No attributes: when the script must execute before the page is displayed