Optimize Third Party Scripts in Next.js for Better Performance
In Next.js, optimize third party scripts by using the
next/script component with the strategy prop to control when scripts load, such as lazyOnload or afterInteractive. This defers script loading to improve page speed and reduce blocking of main content rendering.Syntax
The next/script component lets you add third party scripts with control over loading behavior. Key parts:
src: URL of the script.strategy: When to load the script. Options includebeforeInteractive,afterInteractive, andlazyOnload.onLoad: Callback when script finishes loading.
javascript
import Script from 'next/script'; export default function MyComponent() { return ( <> <Script src="https://example.com/script.js" strategy="lazyOnload" onLoad={() => console.log('Script loaded')} /> </> ); }
Example
This example shows how to load Google Analytics script after the page is interactive to avoid blocking the main content. It uses strategy="afterInteractive" to defer loading.
javascript
import Script from 'next/script'; export default function Home() { return ( <> <h1>Welcome to My Site</h1> <Script src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID" strategy="afterInteractive" /> <Script id="google-analytics" strategy="afterInteractive" dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'GA_MEASUREMENT_ID'); `, }} /> </> ); }
Output
<h1>Welcome to My Site</h1> (Google Analytics script loads after page interaction)
Common Pitfalls
Common mistakes when adding third party scripts in Next.js include:
- Loading scripts with
strategy="beforeInteractive"unnecessarily, which blocks page rendering. - Not using
next/scriptand adding scripts directly in_document.js, losing control over loading timing. - Forgetting to add
idoronLoadhandlers to track script status.
javascript
/* Wrong way: Adding script directly in _document.js without control */ // pages/_document.js import { Html, Head, Main, NextScript } from 'next/document'; export default function Document() { return ( <Html> <Head> <script src="https://example.com/script.js"></script> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } /* Right way: Using next/script with strategy */ import Script from 'next/script'; export default function MyPage() { return ( <> <Script src="https://example.com/script.js" strategy="lazyOnload" /> <main>Page content</main> </> ); }
Quick Reference
Summary tips for optimizing third party scripts in Next.js:
- Use
next/scriptcomponent for all external scripts. - Choose
strategywisely:afterInteractivefor scripts needed soon after load,lazyOnloadfor non-critical scripts. - Use
onLoadto handle script load events. - Avoid blocking rendering by not using
beforeInteractiveunless necessary. - Test performance impact with browser DevTools network and performance tabs.
Key Takeaways
Always use the next/script component to load third party scripts in Next.js.
Set the strategy prop to defer script loading and avoid blocking page rendering.
Use afterInteractive for scripts needed soon after page load and lazyOnload for less critical scripts.
Avoid adding scripts directly in _document.js to keep control over loading behavior.
Monitor script loading with onLoad callbacks and browser DevTools for best performance.