Script Component

Examples

Version History

VersionChanges
v12.2.4onReady prop added.
v12.2.2Allow next/script with beforeInteractive to be placed in _document.
v11.0.0next/script introduced.

The Next.js Script component, next/script, is an extension of the HTML <script> element. It enables developers to set the loading priority of third-party scripts anywhere in their application, outside next/head, saving developer time while improving loading performance.

  1. import Script from 'next/script'
  2. export default function Home() {
  3. return (
  4. <>
  5. <Script src="https://www.google-analytics.com/analytics.js" />
  6. </>
  7. )
  8. }

Overview

Websites often use third-party scripts to include different types of functionality into their site, such as analytics, ads, customer support widgets, and consent management. However, this can introduce problems that impact both user and developer experience:

  • Some third-party scripts are heavy on loading performance and can drag down the user experience, especially if they are render-blocking and delay any page content from loading
  • Developers often struggle to decide where to place third-party scripts in an application to ensure optimal loading

The Script component makes it easier for developers to place a third-party script anywhere in their application while taking care of optimizing its loading strategy.

Usage

To add a third-party script to your application, import the next/script component:

  1. import Script from 'next/script'

Strategy

With next/script, you decide when to load your third-party script by using the strategy property:

  1. <Script src="https://connect.facebook.net/en_US/sdk.js" strategy="lazyOnload" />

There are four different loading strategies that can be used:

  • beforeInteractive: Load before the page is interactive
  • afterInteractive: (default) Load immediately after the page becomes interactive
  • lazyOnload: Load during idle time
  • worker: (experimental) Load in a web worker

beforeInteractive

Scripts that load with the beforeInteractive strategy are injected into the initial HTML from the server and run before self-bundled JavaScript is executed. This strategy should be used for any critical scripts that need to be fetched and executed before any page becomes interactive. This strategy only works inside _document.js and is designed to load scripts that are needed by the entire site (i.e. the script will load when any page in the application has been loaded server-side).

The reason beforeInteractive was designed to work only inside \_document.js is to support streaming and Suspense functionality. Outside of the _document, it’s not possible to guarantee the timing or ordering of beforeInteractive scripts.

  1. // In _document.js
  2. import { Html, Head, Main, NextScript } from 'next/document'
  3. import Script from 'next/script'
  4. export default function Document() {
  5. return (
  6. <Html>
  7. <Head />
  8. <body>
  9. <Main />
  10. <NextScript />
  11. <Script
  12. src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
  13. strategy="beforeInteractive"
  14. ></Script>
  15. </body>
  16. </Html>
  17. )
  18. }

Note: Scripts with beforeInteractive will always be injected inside the head of the HTML document regardless of where it’s placed in _document.js.

Examples of scripts that should be loaded as soon as possible with this strategy include:

  • Bot detectors
  • Cookie consent managers

afterInteractive

Scripts that use the afterInteractive strategy are injected client-side and will run after Next.js hydrates the page. This strategy should be used for scripts that do not need to load as soon as possible and can be fetched and executed immediately after the page is interactive.

  1. <Script
  2. id="google-analytics"
  3. strategy="afterInteractive"
  4. dangerouslySetInnerHTML={{
  5. __html: `
  6. (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  7. new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  8. j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  9. 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  10. })(window,document,'script','dataLayer', 'GTM-XXXXXX');
  11. `,
  12. }}
  13. />

Examples of scripts that are good candidates to load immediately after the page becomes interactive include:

  • Tag managers
  • Analytics

lazyOnload

Scripts that use the lazyOnload strategy are loaded late after all resources have been fetched and during idle time. This strategy should be used for background or low priority scripts that do not need to load before or immediately after a page becomes interactive.

  1. <Script src="https://connect.facebook.net/en_US/sdk.js" strategy="lazyOnload" />

Examples of scripts that do not need to load immediately and can be lazy-loaded include:

  • Chat support plugins
  • Social media widgets

Off-loading Scripts To A Web Worker (experimental)

Note: The worker strategy is not yet stable and can cause unexpected issues in your application. Use with caution.

Scripts that use the worker strategy are relocated and executed in a web worker with Partytown. This can improve the performance of your site by dedicating the main thread to the rest of your application code.

This strategy is still experimental and can only be used if the nextScriptWorkers flag is enabled in next.config.js:

  1. module.exports = {
  2. experimental: {
  3. nextScriptWorkers: true,
  4. },
  5. }

Then, run next (normally npm run dev or yarn dev) and Next.js will guide you through the installation of the required packages to finish the setup:

  1. npm run dev
  2. # You'll see instructions like these:
  3. #
  4. # Please install Partytown by running:
  5. #
  6. # npm install @builder.io/partytown
  7. #
  8. # ...

Once setup is complete, defining strategy="worker" will automatically instantiate Partytown in your application and off-load the script to a web worker.

  1. <Script src="https://example.com/analytics.js" strategy="worker" />

There are a number of trade-offs that need to be considered when loading a third-party script in a web worker. Please see Partytown’s Trade-Offs documentation for more information.

Configuration

Although the worker strategy does not require any additional configuration to work, Partytown supports the use of a config object to modify some of its settings, including enabling debug mode and forwarding events and triggers.

If you would like to add additional configuration options, you can include it within the <Head /> component used in a custom _document.js:

  1. import { Html, Head, Main, NextScript } from 'next/document'
  2. export default function Document() {
  3. return (
  4. <Html>
  5. <Head>
  6. <script
  7. data-partytown-config
  8. dangerouslySetInnerHTML={{
  9. __html: `
  10. partytown = {
  11. lib: "/_next/static/~partytown/",
  12. debug: true
  13. };
  14. `,
  15. }}
  16. />
  17. </Head>
  18. <body>
  19. <Main />
  20. <NextScript />
  21. </body>
  22. </Html>
  23. )
  24. }

In order to modify Partytown’s configuration, the following conditions must be met:

  1. The data-partytown-config attribute must be used in order to overwrite the default configuration used by Next.js
  2. Unless you decide to save Partytown’s library files in a separate directory, the lib: "/_next/static/~partytown/" property and value must be included in the configuration object in order to let Partytown know where Next.js stores the necessary static files.

Note: If you are using an asset prefix and would like to modify Partytown’s default configuration, you must include it as part of the lib path.

Take a look at Partytown’s configuration options to see the full list of other properties that can be added.

Inline Scripts

Inline scripts, or scripts not loaded from an external file, are also supported by the Script component. They can be written by placing the JavaScript within curly braces:

  1. <Script id="show-banner" strategy="lazyOnload">
  2. {`document.getElementById('banner').classList.remove('hidden')`}
  3. </Script>

Or by using the dangerouslySetInnerHTML property:

  1. <Script
  2. id="show-banner"
  3. strategy="lazyOnload"
  4. dangerouslySetInnerHTML={{
  5. __html: `document.getElementById('banner').classList.remove('hidden')`,
  6. }}
  7. />

The id property is required for inline scripts in order for Next.js to track and optimize the script.

Executing Code After Loading (onLoad)

Note: onLoad cannot be used with the beforeInteractive loading strategy. Consider using onReady instead.

Some third-party scripts require users to run JavaScript code once after the script has finished loading in order to instantiate content or call a function. If you are loading a script with either afterInteractive or lazyOnload as a loading strategy, you can execute code after it has loaded using the onLoad property:

  1. import { useState } from 'react'
  2. import Script from 'next/script'
  3. export default function Home() {
  4. const [stripe, setStripe] = useState(null)
  5. return (
  6. <>
  7. <Script
  8. id="stripe-js"
  9. src="https://js.stripe.com/v3/"
  10. onLoad={() => {
  11. setStripe({ stripe: window.Stripe('pk_test_12345') })
  12. }}
  13. />
  14. </>
  15. )
  16. }

Executing Code After Mounting (onReady)

Some third-party scripts require users to run JavaScript code after the script has finished loading and every time the component is mounted (after a route navigation for example). You can execute code after the script’s load event when it first loads and then after every subsequent component re-mount using the onReady property:

  1. import { useRef } from 'react'
  2. import Script from 'next/script'
  3. export default function Home() {
  4. const mapRef = useRef()
  5. return (
  6. <>
  7. <div ref={mapRef}></div>
  8. <Script
  9. id="google-maps"
  10. src="https://maps.googleapis.com/maps/api/js"
  11. onReady={() => {
  12. new google.maps.Map(mapRef.current, {
  13. center: { lat: -34.397, lng: 150.644 },
  14. zoom: 8,
  15. })
  16. }}
  17. />
  18. </>
  19. )
  20. }

Handling errors (onError)

Note: onError cannot be used with the beforeInteractive loading strategy.

Sometimes it is helpful to catch when a script fails to load. These errors can be handled with the onError property:

  1. import Script from 'next/script'
  2. export default function Home() {
  3. return (
  4. <>
  5. <Script
  6. id="will-fail"
  7. src="https://example.com/non-existant-script.js"
  8. onError={(e) => {
  9. console.error('Script failed to load', e)
  10. }}
  11. />
  12. </>
  13. )
  14. }

Additional Attributes

There are many DOM attributes that can be assigned to a <script> element that are not used by the Script component, like nonce or custom data attributes. Including any additional attributes will automatically forward it to the final, optimized <script> element that is outputted to the page.

  1. import Script from 'next/script'
  2. export default function Home() {
  3. return (
  4. <>
  5. <Script
  6. src="https://www.google-analytics.com/analytics.js"
  7. id="analytics"
  8. nonce="XUENAJFW"
  9. data-test="analytics"
  10. />
  11. </>
  12. )
  13. }