Lesson 28 +10 XP

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:

StrategyWhen ExecutedIdeal Use Case
afterInteractive (Default)Immediately after page becomes interactiveAnalytics, Tag Managers, Ad trackers
beforeInteractiveInjected into HTML head before page hydrationCookie consent banners, bot detectors
lazyOnloadDuring browser idle time after page loadsChat widgets, social media embeds
worker (Experimental)Offloads script execution to Web WorkerHeavy 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 /> from next/script for 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 id prop.