跳到內容

Script

此 API 參考將幫助您了解如何使用 Script 元件可用的 props。如需功能和用法,請參閱最佳化 Scripts 頁面。

app/dashboard/page.tsx
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:(預設)提早載入,但在頁面上發生一些 hydration 之後。
  • lazyOnload:在瀏覽器閒置時間載入。
  • worker:(實驗性)在 Web Worker 中載入。

beforeInteractive

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

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

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

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

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 中,並在頁面上發生一些(或全部)hydration 之後載入。這是 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 Router。請謹慎使用。

使用 worker 策略的腳本會卸載到 Web Worker,以釋放主線程並確保僅在主線程上處理關鍵的第一方資源。雖然此策略可用於任何腳本,但它是一種進階使用案例,不能保證支援所有第三方腳本。

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

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

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

pages/home.tsx
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 程式碼,以便實例化內容或呼叫函式。如果您使用 afterInteractivelazyOnload 作為載入策略載入腳本,則可以使用 onLoad 屬性在腳本載入後執行程式碼。

以下範例說明僅在載入 lodash 函式庫後才執行 lodash 方法。

app/page.tsx
'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 嵌入

app/page.tsx
'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 尚不適用於伺服器元件,且僅能用於用戶端元件。onError 無法與 beforeInteractive 載入策略一起使用。

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

app/page.tsx
'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 prop。
v12.2.2允許將具有 beforeInteractivenext/script 放置在 _document 中。
v11.0.0引入 next/script