MENU
Script
There are four different strategies that can be used to load a <Script>:
-
beforeInteractive: Load prior to any Next.js code execution and before the hydration of any page begins.
The beforeInteractive strategy loads scripts early by injecting them into the initial server-rendered HTML. These scripts execute before any Next.js modules and page hydration, without blocking interactivity.- Placement: Must be in app/layout.tsx for global availability.
- Use Case: For critical functionality like bot detection or cookie consent.
- Injection: Always added to the of the HTML document.
-
afterInteractive: (Default) Load early, but only after partial hydration of the page has started.
The afterInteractive strategy, the default for the Script component, loads scripts client-side after some or all page hydration.- Placement: Can be added to any page or layout, loading only when that page or group of pages is viewed.
- Use Case: Ideal for scripts that should load quickly but not before Next.js code, such as tag managers and nalytics
-
lazyOnload: Load when the browser is idle.
Scripts using the lazyOnload strategy are injected client-side during the browser's idle time, loading only after all page resources have been fetched. This strategy is ideal for low-priority or background scripts that don't require early execution.- Placement: Can be added to any page or layout, loading only when the specific page or group of pages is accessed.
- Use Case: Best suited for non-essential scripts such as chat support plugins and social media widgets.
-
worker: (experimental) Load in a web worker.
The worker strategy is experimental and incompatible with the app directory. It offloads scripts to a web worker to free the main thread, focusing it on critical first-party resources.- Advanced Use: May not support all third-party scripts.
- Requirement: Enable the nextScriptWorkers flag in next.config.js.
- Warning: Use cautiously due to instability.
Press F12 to read the log on the browser console.
Notice the file myscript.js is placed in the public folder.
To load a third-party script for all routes in Next.js, import next/script and include the script in the root layout. It will execute only once across the app, even during navigation.
Add scripts only to specific pages or layouts to minimize performance impact.
Any extra DOM attributes like nonce or custom data attributes are automatically forwarded to the final <script> element.
Inline scripts are also supported.
<Script id="show-banner">
{`document.getElementById('banner').classList.remove('hidden')`}
</Script>
<Script
id="show-banner"
dangerouslySetInnerHTML={{
__html: `document.getElementById('banner').classList.remove('hidden')`,
}}
/>