How to Optimize Third-Party Scripts in Next.js

Sometime your app requires third-party JavaScript to work, such as when you're loading Google ads, or some other third-party services. How you are loading the scripts can make a huge difference in terms of the overall performance of the app.

Next.js recommends using the built-in <Script> component when dealing with third-party scripts.

jsx
1import Script from "next/script";
2
3export default function Page() {
4  return <Script src="https://example.com/script.js" />;
5}

Loading strategy

The <Script> component allows you to define a strategy prop, which determines how you want the script to be loaded.

jsx
1import Script from "next/script";
2
3export default function Page() {
4  return (
5    <div>
6      <p>Lorem ipsum dolor . . .</p>
7      <Script
8        src="https://example.com/script.js"
9        strategy="beforeInteractive"
10      />
11    </div>
12  );
13}

The strategy prop accepts the following options:

  • beforeInteractive: The script will be placed in the <head> section, and will be loaded before the rest of the page.
  • afterInteractive: This is the default option. The script will be placed right before the closing </body> tag, and will be loaded right after the page finishes hydrating.
  • lazyOnload: The script will be loaded after the page finishes loading, when the browser is idle.

Inline scripts

This is rarely used, but the <Script> component allows you to add inline scripts as well:

Wait, there is more!

Please create an account to access this content.

From HTML & CSS to JavaScript, from basic language syntaxes to web development frameworks, from the frontend to the backend, we'll guide you through every step of your coding journey.

🎉 Create an Account 🎉