Capítulo 369 de 456
next/script optimizes loading of third-party scripts by controlling exactly when they execute relative to hydration.
src: required unless using an inline script.strategy: beforeInteractive, afterInteractive (default), lazyOnload, worker (experimental).beforeInteractive: injected in initial HTML, executed before any Next.js code; must live in pages/_document.js.afterInteractive: loads after some hydration; default, usable in any page/layout.lazyOnload: loads during browser idle time; for low-priority scripts.worker: offloads to a web worker (needs experimental.nextScriptWorkers in next.config.js; Pages Router only, not App Router).onLoad / onReady / onError: callbacks after load, after every mount, and on load failure respectively; only work in Client Components, not usable with beforeInteractive (except onReady, which also can't be used with Server Components).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 scripts must go in _document.js and always inject into <head>.| Prop | Type | Required |
|---|---|---|
src | String | required unless inline |
strategy | String | - |
onLoad | Function | - |
onReady | Function | - |
onError | Function | - |
beforeInteractive for non-critical scripts: blocks nothing but delays hydration priority; reserve for bot detectors/cookie consent only.onLoad with beforeInteractive: unsupported combination; use onReady instead.worker strategy in production without testing: still experimental and not App Router compatible.beforeInteractive, needed soon → afterInteractive, deferrable → lazyOnload.beforeInteractive scripts must be in _document.js; the rest can live in any page/layout and load only when that page mounts.onLoad/onReady/onError require Client Components ('use client').beforeInteractive scripts.