Load Tag Managers, Analytics, Chat Widgets Strategically
next/script — Third-Party Scripts
`next/script` defers third-party scripts so they don't block your page on first paint.
What you'll learn
- Use `Script` with the right `strategy`
- Wire up `src`, `onLoad`, and `onError`
- Avoid loading on every page when you only need one
Third-party scripts are the most common Lighthouse-tanking offender. next/script gives
you precise control over when each one loads.
Basic Usage
import Script from 'next/script'
export default function Analytics() {
return (
<Script
src="https://www.googletagmanager.com/gtag/js?id=GA_ID"
strategy="afterInteractive"
/>
)
} strategy is the key prop — it tells Next when in the page lifecycle to insert and run
the script.
The Four Strategies
beforeInteractive— loads before hydration. Use rarely; blocks paint.afterInteractive(default) — loads after hydration. Right choice for analytics.lazyOnload— waits for the browser to be idle. Use for chat widgets, marketing pixels.worker(experimental) — runs the script off-thread via Partytown.
Inline Scripts
<Script id="dataLayer-init" strategy="afterInteractive">
{`window.dataLayer = window.dataLayer || []; dataLayer.push({ page: 'home' });`}
</Script> Always give inline scripts a stable id so Next can dedupe them.
Scope It
Only render <Script> on the pages that need it. A RootLayout is the wrong place for
a chat widget that only the marketing site uses — move it to a more specific layout
or page.