Next.js › Third-Party Script Optimization
How do you run code after a third party script has finished loading?
IntermediateAnswer
You pass an onLoad callback function to the Script component, which Next.js automatically calls once the script has fully finished loading, letting you safely run any code that depends on that script being available, such as initializing a library after it loads.
<Script
src="https://maps.example.com/api.js"
strategy="afterInteractive"
onLoad={() => {
initializeMap();
}}
/>Real-world example A website waits for a mapping library to fully load before trying to initialize an interactive map on the page, avoiding errors that would occur if the code tried to use the library before it was ready.