<Script>

本 API 參考將幫助您了解如何使用 Script 元件提供的 props。關於功能和用法,請參閱 優化腳本 頁面。

import Script from 'next/script'

export default function Dashboard() {
  return (
    <>
      <Script src="https://example.com/script.js" />
    </>
  )
}

Props

以下是 Script 元件可用的 props 摘要:

Prop範例類型必填
srcsrc="http://example.com/script"字串除非使用內聯腳本,否則必填
strategystrategy="lazyOnload"字串-
onLoadonLoad={onLoadFunc}函式-
onReadyonReady={onReadyFunc}函式-
onErroronError={onErrorFunc}函式-

必填 Props

<Script /> 元件需要以下屬性。

src

指定外部腳本 URL 的路徑字串。可以是絕對外部 URL 或內部路徑。除非使用內聯腳本,否則 src 屬性為必填。

選填 Props

<Script /> 元件接受許多超出必填屬性的附加屬性。

strategy

腳本的載入策略。有四種不同的策略可以使用:

  • beforeInteractive: 在任何 Next.js 代碼之前載入,並在頁面任何水合 (hydration) 發生之前執行。
  • afterInteractive: (預設) 在頁面部分水合後早期載入。
  • lazyOnload: 在瀏覽器空閒時間載入。
  • worker: (實驗性) 在 web worker 中載入。

beforeInteractive

使用 beforeInteractive 策略載入的腳本會從伺服器注入到初始 HTML 中,在任何 Next.js 模組之前下載,並在頁面上 任何 水合發生之前按放置順序執行。

標記此策略的腳本會預先載入並在任何第一方代碼之前獲取,但它們的執行不會阻止頁面水合的發生。

beforeInteractive 腳本必須放置在根布局 (app/layout.tsx) 中,並設計用於載入整個網站所需的腳本(即當應用程式的任何頁面在伺服器端載入時,腳本都會載入)。

此策略僅應用於需要在頁面任何部分變得可互動之前獲取的關鍵腳本。

import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'

export default function Document() {
  return (
    <Html>
      <Head />
      <body>
        <Main />
        <NextScript />
        <Script
          src="https://example.com/script.js"
          strategy="beforeInteractive"
        />
      </body>
    </Html>
  )
}

須知:無論放置在元件中的哪個位置,beforeInteractive 腳本始終會注入到 HTML 文件的 head 中。

一些應盡快使用 beforeInteractive 載入的腳本範例包括:

  • 機器人檢測器
  • Cookie 同意管理器

afterInteractive

使用 afterInteractive 策略的腳本會在客戶端注入到 HTML 中,並在頁面上部分(或全部)水合後載入。這是 Script 元件的預設策略,應用于任何需要盡快載入但不必在任何第一方 Next.js 代碼之前載入的腳本。

afterInteractive 腳本可以放置在任何頁面或布局中,並且僅在該頁面(或頁面組)在瀏覽器中打開時才會載入和執行。

app/page.js
import Script from 'next/script'

export default function Page() {
  return (
    <>
      <Script src="https://example.com/script.js" strategy="afterInteractive" />
    </>
  )
}

一些適合使用 afterInteractive 的腳本範例包括:

  • 標籤管理器
  • 分析工具

lazyOnload

使用 lazyOnload 策略的腳本會在瀏覽器空閒時間客戶端注入到 HTML 中,並在頁面上所有資源獲取完成後載入。此策略應用于任何不需要早期載入的背景或低優先級腳本。

lazyOnload 腳本可以放置在任何頁面或布局中,並且僅在該頁面(或頁面組)在瀏覽器中打開時才會載入和執行。

app/page.js
import Script from 'next/script'

export default function Page() {
  return (
    <>
      <Script src="https://example.com/script.js" strategy="lazyOnload" />
    </>
  )
}

不需要立即載入並可以使用 lazyOnload 獲取的腳本範例包括:

  • 聊天支援插件
  • 社交媒體小工具

worker

警告worker 策略尚未穩定,且尚不適用於 app 目錄。請謹慎使用。

使用 worker 策略的腳本會被卸載到 web worker 中,以釋放主線程並確保僅處理關鍵的第一方資源。雖然此策略可用于任何腳本,但這是一個高級用例,不保證支持所有第三方腳本。

要使用 worker 作為策略,必須在 next.config.js 中啟用 nextScriptWorkers 標誌:

next.config.js
module.exports = {
  experimental: {
    nextScriptWorkers: true,
  },
}

worker 腳本目前 僅能在 pages/ 目錄中使用

import Script from 'next/script'

export default function Home() {
  return (
    <>
      <Script src="https://example.com/script.js" strategy="worker" />
    </>
  )
}

onLoad

警告onLoad 尚不適用於伺服器元件,僅能在客戶端元件中使用。此外,onLoad 不能與 beforeInteractive 一起使用 — 請考慮改用 onReady

某些第三方腳本要求使用者在腳本載入完成後運行 JavaScript 代碼以實例化內容或調用函式。如果您使用 afterInteractive 或 lazyOnload 作為載入策略,則可以使用 onLoad 屬性在腳本載入後執行代碼。

以下是一個僅在 lodash 庫載入後執行方法的範例。

'use client'

import Script from 'next/script'

export default function Page() {
  return (
    <>
      <Script
        src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"
        onLoad={() => {
          console.log(_.sample([1, 2, 3, 4]))
        }}
      />
    </>
  )
}

onReady

警告onReady 尚不適用於伺服器元件,僅能在客戶端元件中使用。

某些第三方腳本要求使用者在腳本載入完成後以及每次元件掛載時(例如在路由導航後)運行 JavaScript 代碼。您可以使用 onReady 屬性在腳本首次載入的 load 事件後以及每次後續元件重新掛載後執行代碼。

以下是一個在每次元件掛載時重新實例化 Google Maps JS 嵌入的範例:

import { useRef } from 'react';
import Script from 'next/script';

export default function Page() {
  const mapRef = useRef();

  return (
    <PagesOnly>
      <div ref={mapRef}></div>
      <Script
        id="google-maps"
        src="https://maps.googleapis.com/maps/api/js"
        onReady={() => {
          new google.maps.Map(mapRef.current, {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8,
          });
        }}
      />
    </>
  );
}

onError

警告onError 尚不適用於伺服器元件,僅能在客戶端元件中使用。onError 不能與 beforeInteractive 載入策略一起使用。

有時捕捉腳本載入失敗的情況很有幫助。這些錯誤可以通過 onError 屬性處理:

import Script from 'next/script'

export default function Page() {
  return (
    <>
      <Script
        src="https://example.com/script.js"
        onError={(e: Error) => {
          console.error('Script failed to load', e)
        }}
      />
    </>
  )
}

版本歷史

版本變更
v13.0.0beforeInteractiveafterInteractive 修改以支援 app
v12.2.4新增 onReady prop。
v12.2.2允許 next/scriptbeforeInteractive 放置在 _document 中。
v11.0.0引入 next/script

On this page