| 1 | --- |
| 2 | title: Use defer or async on Script Tags |
| 3 | impact: HIGH |
| 4 | impactDescription: eliminates render-blocking |
| 5 | tags: rendering, script, defer, async, performance |
| 6 | --- |
| 7 | |
| 8 | ## Use defer or async on Script Tags |
| 9 | |
| 10 | **Impact: HIGH (eliminates render-blocking)** |
| 11 | |
| 12 | Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive. |
| 13 | |
| 14 | - **`defer` |
| 15 | - **`async` |
| 16 | |
| 17 | Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics. |
| 18 | |
| 19 | **Incorrect (blocks rendering):** |
| 20 | |
| 21 | ```tsx |
| 22 | export default function Document |
| 23 | return ( |
| 24 | <html> |
| 25 | <head> |
| 26 | <script src=" |
| 27 | <script src=" |
| 28 | </head> |
| 29 | <body>{/* content |
| 30 | </html> |
| 31 | ); |
| 32 | } |
| 33 | ``` |
| 34 | |
| 35 | **Correct (non-blocking):** |
| 36 | |
| 37 | ```tsx |
| 38 | export default function Document |
| 39 | return ( |
| 40 | <html> |
| 41 | <head> |
| 42 | {/* Independent script - use async */ |
| 43 | <script src=" |
| 44 | {/* DOM-dependent script - use defer */ |
| 45 | <script src=" |
| 46 | </head> |
| 47 | <body>{/* content |
| 48 | </html> |
| 49 | ); |
| 50 | } |
| 51 | ``` |
| 52 | |
| 53 | **Note:** In Next.js, prefer the `next/script |
| 54 | |
| 55 | ```tsx |
| 56 | import Script from "next/script |
| 57 | |
| 58 | export default function Page |
| 59 | return ( |
| 60 | <> |
| 61 | <Script src= |
| 62 | <Script src= |
| 63 | </> |
| 64 | ); |
| 65 | } |
| 66 | ``` |
| 67 | |
| 68 | Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer |