How to Use next/script in Next.js for Optimized Script Loading
Use the
next/script component to add external or inline scripts in Next.js pages or components. It allows you to control when and how scripts load using the strategy prop, improving performance and avoiding blocking rendering.Syntax
The next/script component accepts these main props:
- src: URL of the external script.
- strategy: When to load the script. Options are
beforeInteractive,afterInteractive, andlazyOnload. - onLoad: Callback when the script loads.
- id: Unique identifier for inline scripts.
- children: Inline script content.
jsx
import Script from 'next/script'; export default function MyComponent() { return ( <> <Script src="https://example.com/script.js" strategy="afterInteractive" onLoad={() => console.log('Script loaded')} /> <Script id="inline-script" strategy="lazyOnload"> {`console.log('Inline script runs')`} </Script> </> ); }
Example
This example shows how to load Google Analytics script after the page is interactive and run an inline script lazily after the page load.
jsx
import Script from 'next/script'; export default function Home() { return ( <> <h1>Welcome to Next.js</h1> {/* Load external script after page is interactive */} <Script src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID" strategy="afterInteractive" /> {/* Inline script to initialize Google Analytics */} <Script id="ga-init" strategy="afterInteractive"> {`window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'GA_MEASUREMENT_ID');`} </Script> </> ); }
Output
<h1>Welcome to Next.js</h1> (Google Analytics script loads after page is interactive)
Common Pitfalls
- Not setting
strategycan cause scripts to block page rendering or load too late. - Using multiple scripts with the same
idcauses errors for inline scripts. - Loading scripts that depend on DOM before it is ready can cause errors.
- For scripts that must run before page interaction, use
beforeInteractivestrategy.
jsx
/* Wrong: No strategy causes blocking */ <Script src="https://example.com/script.js" /> /* Right: Use strategy to control loading */ <Script src="https://example.com/script.js" strategy="afterInteractive" />
Quick Reference
| Prop | Description | Common Values |
|---|---|---|
| src | URL of external script | https://example.com/script.js |
| strategy | When to load the script | beforeInteractive, afterInteractive, lazyOnload |
| id | Unique ID for inline scripts | string |
| onLoad | Callback after script loads | () => {} |
| children | Inline script content | JavaScript code string |
Key Takeaways
Use
next/script to load scripts efficiently in Next.js.Set the
strategy prop to control script loading timing.Use
beforeInteractive for scripts needed before user interaction.Avoid duplicate
id props for inline scripts to prevent errors.Inline scripts go inside
children with a unique id.