typescriptbeginner

Script Component Loading Strategies

Load third-party scripts efficiently with next/script using different loading strategies.

typescript
// app/layout.tsx
import Script from 'next/script';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        {children}

        {/* beforeInteractive — loads before page hydration */}
        <Script
          src="https://cdn.polyfill.io/v3/polyfill.min.js"
          strategy="beforeInteractive"
        />

        {/* afterInteractive (default) — loads after hydration */}
        <Script
          src="https://www.googletagmanager.com/gtag/js?id=G-XXXX"
          strategy="afterInteractive"
        />
        <Script id="gtag-init" strategy="afterInteractive">
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'G-XXXX');
          `}
        </Script>

        {/* lazyOnload — loads during idle time */}
        <Script
          src="https://cdn.chatwidget.com/widget.js"
          strategy="lazyOnload"
          onLoad={() => console.log('Chat widget loaded')}
        />

        {/* worker — loads in web worker (experimental) */}
        <Script
          src="https://analytics.example.com/tracker.js"
          strategy="worker"
        />
      </body>
    </html>
  );
}

// Using onLoad and onError callbacks
// <Script
//   src="https://maps.googleapis.com/maps/api/js"
//   onLoad={() => initMap()}
//   onError={(e) => console.error('Failed to load maps', e)}
// />

Use Cases

  • analytics
  • chat widgets
  • third-party integrations

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.