Next.js Script Optimization explains how to manage external JavaScript SDKs, tracking pixels, and third-party tools using the built-in <Script> component.
Loading third-party scripts using standard <script> tags can block page rendering and hurt web performance. Next.js provides loading strategy options to control script execution cleanly.
Import Script from next/script and define script execution strategies:
// app/layout.tsx
import Script from 'next/script';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
{/* Third-party analytics script */}
<Script
src="https://example.com/analytics.js"
strategy="afterInteractive"
/>
</body>
</html>
);
}
Select script strategies based on execution priority:
| Strategy | When It Executes | Best Use Cases |
|---|---|---|
beforeInteractive |
Before page hydration | Essential bot detection, security cookies |
afterInteractive |
Immediately after hydration (default) | Analytics, tag managers, advertising scripts |
lazyOnload |
During browser idle time | Live chat widgets, feedback widgets |
worker |
Inside a Web Worker (experimental) | Heavy background processing scripts |
Run inline code snippets safely by supplying children or dangerouslySetInnerHTML props:
// app/components/Analytics.tsx
import Script from 'next/script';
export default function Analytics() {
return (
<Script id="analytics-init" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA-TRACKING-ID');
`}
</Script>
);
}
id Props: Provide a unique id attribute when using inline script definitions.lazyOnload for Low-Priority Widgets: Defer non-critical customer support widgets to idle browser time to keep initial renders fast.The Next.js <Script> component gives you fine-grained control over external third-party scripts, keeping your initial page loads fast and responsive.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.