Back to results for “Monitoring”
Next.js › Third-Party Script Optimization

How do you run code after a third party script has finished loading?

Intermediate

Answer

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.

Common follow-ups: What happens if you try to use a library before its script has finished loading?;Can you also handle a script loading error using the Script component?