Script Strategies

next/script

Third-party scripts (analytics, chat widgets, payment SDKs) are a top cause of slow pages. <Script> controls when they load:

strategyLoadsUse for
beforeInteractiveBefore hydration (root layout only)Bot detection, consent managers
afterInteractive (default)Right after hydrationAnalytics, tag managers
lazyOnloadWhen the browser is idleChat widgets, social embeds
worker (experimental)In a web worker (Partytown)Heavy third-party scripts

Examples

import Script from 'next/script';

export default function CheckoutLayout({ children }: { children: React.ReactNode }) {
  return (
    <>
      {children}
      {/* Payment SDK only on checkout pages, not site-wide */}
      <Script src="https://checkout.razorpay.com/v1/checkout.js" strategy="afterInteractive" />
      {/* Support chat can wait */}
      <Script src="https://widget.example-chat.com/loader.js" strategy="lazyOnload" />
    </>
  );
}

Tip: For Google Analytics and Google Tag Manager use @next/third-parties/google (<GoogleAnalytics gaId="G-XXXX" />), which loads them efficiently.