<Script>

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

import Script from 'next/script'

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

屬性

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

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

必填屬性

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

src

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

可選屬性

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

strategy

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

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

beforeInteractive

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

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

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

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

import Script from 'next/script'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        {children}
        <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 尚不適用於伺服器元件 (Server Components),且僅能在客戶端元件 (Client Components) 中使用。此外,onLoad 不能與 beforeInteractive 一起使用 — 請考慮改用 onReady

某些第三方腳本要求在腳本加載完成後立即運行 JavaScript 代碼以實例化內容或調用函數。如果您使用 afterInteractivelazyOnload 作為加載策略,則可以使用 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 尚不適用於伺服器元件 (Server Components),且僅能在客戶端元件 (Client Components) 中使用。

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

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

'use client'

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

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

  return (
    <>
      <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 尚不適用於伺服器元件 (Server Components),且僅能在客戶端元件 (Client Components) 中使用。onError 不能與 beforeInteractive 加載策略一起使用。

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

'use client'

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.0修改 beforeInteractiveafterInteractive 以支援 app
v12.2.4新增 onReady 屬性。
v12.2.2允許將 next/scriptbeforeInteractive 放置在 _document 中。
v11.0.0引入 next/script

On this page