Loading lessons...
Script Optimization (next/script)
Script Optimization (next/script)
The <Script /> component from next/script optimizes third-party scripts (analytics, ad networks, chat widgets, cookie consent) by providing control over script loading order and execution timing.
Using Script Components
import Script from 'next/script';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
{/* Third-Party Script (e.g. Analytics) */}
<Script
src="https://example.com/analytics.js"
strategy="afterInteractive"
onLoad={() => {
console.log('Analytics script loaded successfully!');
}}
/>
</body>
</html>
);
}
Loading Strategies (strategy prop)
Next.js provides four distinct loading strategies to prevent third-party scripts from blocking critical page rendering:
| Strategy | When Executed | Ideal Use Case |
|---|---|---|
afterInteractive (Default) | Immediately after page becomes interactive | Analytics, Tag Managers, Ad trackers |
beforeInteractive | Injected into HTML head before page hydration | Cookie consent banners, bot detectors |
lazyOnload | During browser idle time after page loads | Chat widgets, social media embeds |
worker (Experimental) | Offloads script execution to Web Worker | Heavy tracking scripts |
Inline Scripts
To execute inline JavaScript code safely, pass code string inside the component or use dangerouslySetInnerHTML:
<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>
⚠️ DocHero Safety Disclaimer
An id prop is required when writing inline scripts with <Script />.
TL;DR
- Use
<Script />fromnext/scriptfor third-party SDKs and tracking tools. strategy="afterInteractive"(default) loads scripts right after hydration.strategy="lazyOnload"delays script loading until browser idle time.- Inline scripts require a unique
idprop.