脚本
此 API 参考将帮助你了解如何使用可用于脚本组件的 props。功能及使用方法请参见 优化脚本 页。
¥This API reference will help you understand how to use props available for the Script Component. For features and usage, please see the Optimizing Scripts page.
import Script from 'next/script'
export default function Dashboard() {
return (
<>
<Script src="https://example.com/script.js" />
</>
)
}
import Script from 'next/script'
export default function Dashboard() {
return (
<>
<Script src="https://example.com/script.js" />
</>
)
}
属性
¥Props
以下是脚本组件可用的 props 的摘要:
¥Here's a summary of the props available for the Script Component:
属性 | 示例 | 类型 | 必需的 |
---|---|---|---|
src | src="http://example.com/script" | 字符串 | 除非使用内联脚本,否则必需 |
strategy | strategy="lazyOnload" | 字符串 | * |
onLoad | onLoad={onLoadFunc} | 函数 | * |
onReady | onReady={onReadyFunc} | 函数 | * |
onError | onError={onErrorFunc} | 函数 | * |
必需属性
¥Required Props
<Script />
组件需要以下属性。
¥The <Script />
component requires the following properties.
src
指定外部脚本 URL 的路径字符串。这可以是绝对外部 URL 或内部路径。除非使用内联脚本,否则 src
属性是必需的。
¥A path string specifying the URL of an external script. This can be either an absolute external URL or an internal path. The src
property is required unless an inline script is used.
可选属性
¥Optional Props
<Script />
组件接受除所需属性之外的许多附加属性。
¥The <Script />
component accepts a number of additional properties beyond those which are required.
strategy
脚本的加载策略。可以使用四种不同的策略:
¥The loading strategy of the script. There are four different strategies that can be used:
-
beforeInteractive
:在任何 Next.js 代码之前以及任何页面水合发生之前加载。¥
beforeInteractive
: Load before any Next.js code and before any page hydration occurs. -
afterInteractive
:(默认)尽早加载,但要在页面发生一些水合作用之后。¥
afterInteractive
: (default) Load early but after some hydration on the page occurs. -
lazyOnload
:在浏览器空闲时加载。¥
lazyOnload
: Load during browser idle time. -
worker
:(实验性)加载网络工作者。¥
worker
: (experimental) Load in a web worker.
beforeInteractive
使用 beforeInteractive
策略加载的脚本会从服务器注入到初始 HTML 中,在任何 Next.js 模块之前下载,并按照页面上发生任何水合作用之前放置的顺序执行。
¥Scripts that load with the beforeInteractive
strategy are injected into the initial HTML from the server, downloaded before any Next.js module, and executed in the order they are placed before any hydration occurs on the page.
使用此策略表示的脚本在任何第一方代码之前预加载和获取,但它们的执行不会阻止页面水合作用的发生。
¥Scripts denoted with this strategy are preloaded and fetched before any first-party code, but their execution does not block page hydration from occurring.
beforeInteractive
脚本必须放置在根布局 (app/layout.tsx
) 内,并且旨在加载整个站点所需的脚本(即,当应用中的任何页面加载到服务器端时,该脚本将加载)。
¥beforeInteractive
scripts must be placed inside the root layout (app/layout.tsx
) and are 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).
此策略仅应用于需要在页面的任何部分变为交互式之前获取的关键脚本。
¥This strategy should only be used for critical scripts that need to be fetched before any part of the page becomes interactive.
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>
)
}
import Script from 'next/script'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
<Script
src="https://example.com/script.js"
strategy="beforeInteractive"
/>
</body>
</html>
)
}
很高兴知道:带有
beforeInteractive
的脚本将始终被注入到 HTML 文档的head
内,无论它放置在组件中的什么位置。¥Good to know: Scripts with
beforeInteractive
will always be injected inside thehead
of the HTML document regardless of where it's placed in the component.
应尽快使用 beforeInteractive
加载的一些脚本示例包括:
¥Some examples of scripts that should be loaded as soon as possible with beforeInteractive
include:
-
机器人探测器
¥Bot detectors
-
Cookie 同意管理器
¥Cookie consent managers
afterInteractive
使用 afterInteractive
策略的脚本被注入到 HTML 客户端,并在页面上发生部分(或全部)水合作用后加载。这是 Script 组件的默认策略,应该用于任何需要尽快加载但不能在任何第一方 Next.js 代码之前加载的脚本。
¥Scripts that use the afterInteractive
strategy are injected into the HTML client-side and will load after some (or all) hydration occurs on the page. This is the default strategy of the Script component and should be used for any script that needs to load as soon as possible but not before any first-party Next.js code.
afterInteractive
脚本可以放置在任何页面或布局内,并且仅当在浏览器中打开该页面(或页面组)时才会加载和执行。
¥afterInteractive
scripts can be placed inside of any page or layout and will only load and execute when that page (or group of pages) is opened in the browser.
import Script from 'next/script'
export default function Page() {
return (
<>
<Script src="https://example.com/script.js" strategy="afterInteractive" />
</>
)
}
适合 afterInteractive
的一些脚本示例包括:
¥Some examples of scripts that are good candidates for afterInteractive
include:
-
标签管理器
¥Tag managers
-
分析
¥Analytics
lazyOnload
使用 lazyOnload
策略的脚本会在浏览器空闲时注入 HTML 客户端,并在获取页面上的所有资源后加载。此策略应用于不需要提前加载的任何后台或低优先级脚本。
¥Scripts that use the lazyOnload
strategy are injected into the HTML client-side during browser idle time and will load after all resources on the page have been fetched. This strategy should be used for any background or low priority scripts that do not need to load early.
lazyOnload
脚本可以放置在任何页面或布局内,并且仅当在浏览器中打开该页面(或页面组)时才会加载和执行。
¥lazyOnload
scripts can be placed inside of any page or layout and will only load and execute when that page (or group of pages) is opened in the browser.
import Script from 'next/script'
export default function Page() {
return (
<>
<Script src="https://example.com/script.js" strategy="lazyOnload" />
</>
)
}
不需要立即加载并且可以使用 lazyOnload
获取的脚本示例包括:
¥Examples of scripts that do not need to load immediately and can be fetched with lazyOnload
include:
-
聊天支持插件
¥Chat support plugins
-
社交媒体小部件
¥Social media widgets
worker
警告:
worker
策略尚未稳定,尚不能与app
目录配合使用。谨慎使用。¥Warning: The
worker
strategy is not yet stable and does not yet work with theapp
directory. Use with caution.
使用 worker
策略的脚本将被卸载到 Web Worker,以释放主线程并确保仅在其上处理关键的第一方资源。虽然此策略可用于任何脚本,但它是高级用例,不能保证支持所有第三方脚本。
¥Scripts that use the worker
strategy are off-loaded to a web worker in order to free up the main thread and ensure that only critical, first-party resources are processed on it. While this strategy can be used for any script, it is an advanced use case that is not guaranteed to support all third-party scripts.
要使用 worker
作为策略,必须在 next.config.js
中启用 nextScriptWorkers
标志:
¥To use worker
as a strategy, the nextScriptWorkers
flag must be enabled in next.config.js
:
module.exports = {
experimental: {
nextScriptWorkers: true,
},
}
worker
脚本目前只能在 pages/
目录中使用:
¥worker
scripts can only currently be used in the pages/
directory:
import Script from 'next/script'
export default function Home() {
return (
<>
<Script src="https://example.com/script.js" strategy="worker" />
</>
)
}
import Script from 'next/script'
export default function Home() {
return (
<>
<Script src="https://example.com/script.js" strategy="worker" />
</>
)
}
onLoad
警告:
onLoad
尚不能与服务器组件一起使用,只能在客户端组件中使用。此外,onLoad
不能与beforeInteractive
一起使用 - 请考虑使用onReady
。¥Warning:
onLoad
does not yet work with Server Components and can only be used in Client Components. Further,onLoad
can't be used withbeforeInteractive
– consider usingonReady
instead.
某些第三方脚本要求用户在脚本加载完成后运行 JavaScript 代码一次,以便实例化内容或调用函数。如果你使用 afterInteractive 或 lazyOnload 作为加载策略来加载脚本,则可以使用 onLoad 属性在加载后执行代码。
¥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.
下面是仅在加载库后执行 lodash 方法的示例。
¥Here's an example of executing a lodash method only after the library has been loaded.
'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]))
}}
/>
</>
)
}
'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
尚不能与服务器组件一起使用,只能在客户端组件中使用。¥Warning:
onReady
does not yet work with Server Components and can only be used in Client Components.
某些第三方脚本要求用户在脚本完成加载后以及每次安装组件时(例如在路由导航后)运行 JavaScript 代码。你可以在脚本首次加载时的加载事件之后执行代码,然后在使用 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.
下面是如何在每次安装组件时重新实例化 Google Maps JS 嵌入的示例:
¥Here's an example of how to re-instantiate a Google Maps JS embed every time the component is mounted:
'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,
})
}}
/>
</>
)
}
'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
加载策略一起使用。¥Warning:
onError
does not yet work with Server Components and can only be used in Client Components.onError
cannot be used with thebeforeInteractive
loading strategy.
有时,捕获脚本加载失败的情况会很有帮助。这些错误可以使用 onError 属性来处理:
¥Sometimes it is helpful to catch when a script fails to load. These errors can be handled with the onError property:
'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)
}}
/>
</>
)
}
'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)
}}
/>
</>
)
}
版本历史
¥Version History
版本 | 变化 |
---|---|
v13.0.0 | 修改 beforeInteractive 和 afterInteractive 以支持 app 。 |
v12.2.4 | 添加了 onReady 属性。 |
v12.2.2 | 允许将 next/script 和 beforeInteractive 放置在 _document 中。 |
v11.0.0 | next/script 推出。 |