Blog>
Snippets

Optimizing Third-Party Scripts with Next.js Lazy Loading

Implement lazy loading for expensive third-party scripts like analytics or chatbots to improve initial page load time.
import { useEffect } from 'react';
import Script from 'next/script';

const MyPage = () => {
  useEffect(() => {
    const handleRouteChange = () => {
      if (window.myThirdPartyScriptLoaded) {
        // Invoke any specific logic needed once the script has been loaded and route changes.
      }
    };

    // Listen for route changes in your Next.js app
    window.addEventListener('routeChangeComplete', handleRouteChange);

    // Cleanup event listener
    return () => {
      window.removeEventListener('routeChangeComplete', handleRouteChange);
    };
  }, []);

  return (
    <>
      {/* Your page's content */}

      {/* Third-Party Script with onLoad callback */}
      <Script
        src="https://example.com/third-party.js"
        strategy="lazyOnload"
        onLoad={() => {
          window.myThirdPartyScriptLoaded = true;
          // Perform any initialization for the third-party script.
        }}
      />
    </>
  );
};

export default MyPage;
This code snippet is meant to be used in a Next.js application, where the <Script> component from Next.js is being used to lazily load a third-party script. It only loads the script when the user navigates to the particular route where it's required. After the page is loaded, the script is then loaded lazily, and an 'onLoad' callback is used to set a flag indicating the script has been loaded. Additionally, an event listener is added to react to route changes, and this listener is cleaned up when the component unmounts to prevent memory leaks.