Caching Third-Party Scripts with Next.js
Implement a strategy to cache and serve third-party scripts efficiently in a Next.js application, reducing external request overhead.
import Script from 'next/script';
export default function Home() {
return (
<div>
<Script
src="https://third-party-script.com/library.js"
strategy="lazyOnload"
onLoad={() =>
console.log('Script loaded correctly, window.LIBRARY is now available')
}
/>
{/* Rest of the home page */}
</div>
);
}
This code uses the Next.js built-in Script component to load third-party scripts with a 'lazyOnload' strategy. The script will be fetched after the main content of the page has finished loading, which will not block the page rendering. The 'onLoad' callback is used to log a message once the script has been loaded.
import { useEffect } from 'react';
export default function Home() {
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://third-party-script.com/library.js';
script.onload = () => console.log('Script loaded correctly, window.LIBRARY is now available');
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, []);
return (
<div>{/* Rest of the home page */}</div>
);
}
This approach manually creates a script tag using a React effect hook. The script is injected when the component mounts, and upon unmount, the script is removed. This is a more manual way of handling third-party script loading and allows for finer control over caching if combined with a service worker or a caching strategy.