跳至內容

<Script> (指令碼)

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

app/dashboard/page.tsx
import Script from 'next/script'
 
export default function Dashboard() {
  return (
    <>
      <Script src="https://example.com/script.js" />
    </>
  )
}

屬性 (Props)

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

屬性 (Prop)範例類型必要性
來源 (src)src="http://example.com/script"字串 (String)除非使用內嵌腳本,否則為必要
策略 (strategy)strategy="lazyOnload"字串 (String)-
載入時 (onLoad)onLoad={onLoadFunc}函式 (Function)-
準備就緒時 (onReady)onReady={onReadyFunc}函式 (Function)-
錯誤時 (onError)onError={onErrorFunc}函式 (Function)-

必要屬性 (Required Props)

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

src 選用屬性 (Optional Props)

除了必要的屬性之外,<Script /> 元件還接受許多其他屬性。

strategy beforeInteractive

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

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

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

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

pages/_document.js
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
app/page.js
import Script from 'next/script'
 
export default function Page() {
  return (
    <>
      <Script src="https://example.com/script.js" strategy="afterInteractive" />
    </>
  )
}

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

  • 標籤管理員
  • 分析

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/ 目錄中使用

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 屬性在腳本第一次載入時的載入事件之後,以及後續每次元件重新掛載後執行程式碼。

以下是如何在每次元件掛載時重新實例化 Google Maps JS 嵌入的範例。

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 屬性來處理。

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允許在 _document 中放置使用 beforeInteractivenext/script
v11.0.0推出 next/script