File size: 12,066 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 |
---
title: How to load and optimize scripts
nav_title: Scripts
description: Optimize 3rd party scripts with the built-in Script component.
related:
title: API Reference
description: Learn more about the next/script API.
links:
- app/api-reference/components/script
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
<AppOnly>
### Layout Scripts
To load a third-party script for multiple routes, import `next/script` and include the script directly in your layout component:
```tsx filename="app/dashboard/layout.tsx" switcher
import Script from 'next/script'
export default function DashboardLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<>
<section>{children}</section>
<Script src="https://example.com/script.js" />
</>
)
}
```
```jsx filename="app/dashboard/layout.js" switcher
import Script from 'next/script'
export default function DashboardLayout({ children }) {
return (
<>
<section>{children}</section>
<Script src="https://example.com/script.js" />
)
}
```
The third-party script is fetched when the folder route (e.g. `dashboard/page.js`) or any nested route (e.g. `dashboard/settings/page.js`) is accessed by the user. Next.js will ensure the script will **only load once**, even if a user navigates between multiple routes in the same layout.
</AppOnly>
### Application Scripts
<AppOnly>
To load a third-party script for all routes, import `next/script` and include the script directly in your root layout:
```tsx filename="app/layout.tsx" switcher
import Script from 'next/script'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
)
}
```
```jsx filename="app/layout.js" switcher
import Script from 'next/script'
export default function RootLayout({ children }) {
return (
)
}
```
</AppOnly>
<PagesOnly>
To load a third-party script for all routes, import `next/script` and include the script directly in your custom `_app`:
```jsx filename="pages/_app.js"
import Script from 'next/script'
export default function MyApp({ Component, pageProps }) {
return (
)
}
```
</PagesOnly>
This script will load and execute when _any_ route in your application is accessed. Next.js will ensure the script will **only load once**, even if a user navigates between multiple pages.
> **Recommendation**: We recommend only including third-party scripts in specific pages or layouts in order to minimize any unnecessary impact to performance.
### Strategy
Although the default behavior of `next/script` allows you to load third-party scripts in any page or layout, you can fine-tune its loading behavior by using the `strategy` property:
- `beforeInteractive`: Load the script before any Next.js code and before any page hydration occurs.
- `afterInteractive`: (**default**) Load the script early but after some hydration on the page occurs.
- `lazyOnload`: Load the script later during browser idle time.
- `worker`: (experimental) Load the script in a web worker.
Refer to the [`next/script`](/docs/app/api-reference/components/script#strategy) API reference documentation to learn more about each strategy and their use cases.
### Offloading Scripts To A Web Worker (experimental)
> **Warning:** The `worker` strategy is not yet stable and does not yet work with the App Router. Use with caution.
Scripts that use the `worker` strategy are offloaded and executed in a web worker with [Partytown](https://partytown.builder.io/). This can improve the performance of your site by dedicating the main thread to the rest of your application code.
This strategy is still experimental and can only be used if the `nextScriptWorkers` flag is enabled in `next.config.js`:
```js filename="next.config.js"
module.exports = {
experimental: {
nextScriptWorkers: true,
},
}
```
Then, run `next` (normally `npm run dev` or `yarn dev`) and Next.js will guide you through the installation of the required packages to finish the setup:
```bash filename="Terminal"
npm run dev
```
You'll see instructions like these: Please install Partytown by running `npm install @builder.io/partytown`
Once setup is complete, defining `strategy="worker"` will automatically instantiate Partytown in your application and offload the script to a web worker.
```tsx filename="pages/home.tsx" switcher
import Script from 'next/script'
export default function Home() {
return (
)
}
```
```jsx filename="pages/home.js" switcher
import Script from 'next/script'
export default function Home() {
return (
)
}
```
There are a number of trade-offs that need to be considered when loading a third-party script in a web worker. Please see Partytown's [tradeoffs](https://partytown.builder.io/trade-offs) documentation for more information.
<PagesOnly>
#### Using custom Partytown configuration
Although the `worker` strategy does not require any additional configuration to work, Partytown supports the use of a config object to modify some of its settings, including enabling `debug` mode and forwarding events and triggers.
If you would like to add additional configuration options, you can include it within the `<Head />` component used in a [custom `_document.js`](/docs/pages/building-your-application/routing/custom-document):
```jsx filename="_pages/document.jsx"
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
)
}
```
In order to modify Partytown's configuration, the following conditions must be met:
1. The `data-partytown-config` attribute must be used in order to overwrite the default configuration used by Next.js
2. Unless you decide to save Partytown's library files in a separate directory, the `lib: "/_next/static/~partytown/"` property and value must be included in the configuration object in order to let Partytown know where Next.js stores the necessary static files.
> **Note**: If you are using an [asset prefix](/docs/pages/api-reference/config/next-config-js/assetPrefix) and would like to modify Partytown's default configuration, you must include it as part of the `lib` path.
Take a look at Partytown's [configuration options](https://partytown.builder.io/configuration) to see the full list of other properties that can be added.
</PagesOnly>
### Inline Scripts
Inline scripts, or scripts not loaded from an external file, are also supported by the Script component. They can be written by placing the JavaScript within curly braces:
```jsx
<Script id="show-banner">
{`document.getElementById('banner').classList.remove('hidden')`}
</Script>
```
Or by using the `dangerouslySetInnerHTML` property:
```jsx
<Script
id="show-banner"
dangerouslySetInnerHTML={{
__html: `document.getElementById('banner').classList.remove('hidden')`,
}}
/>
```
> **Warning**: An `id` property must be assigned for inline scripts in order for Next.js to track and optimize the script.
### Executing Additional Code
Event handlers can be used with the Script component to execute additional code after a certain event occurs:
- `onLoad`: Execute code after the script has finished loading.
- `onReady`: Execute code after the script has finished loading and every time the component is mounted.
- `onError`: Execute code if the script fails to load.
<AppOnly>
These handlers will only work when `next/script` is imported and used inside of a [Client Component](/docs/app/getting-started/server-and-client-components) where `"use client"` is defined as the first line of code:
```tsx filename="app/page.tsx" switcher
'use client'
import Script from 'next/script'
export default function Page() {
return (
<>
<Script
src="https://example.com/script.js"
onLoad={() => {
console.log('Script has loaded')
}}
/>
</>
)
}
```
```jsx filename="app/page.js" switcher
'use client'
import Script from 'next/script'
export default function Page() {
return (
)
}
```
Refer to the [`next/script`](/docs/app/api-reference/components/script#onload) API reference to learn more about each event handler and view examples.
</AppOnly>
<PagesOnly>
These handlers will only work when `next/script` is imported and used inside of a [Client Component](/docs/app/getting-started/server-and-client-components) where `"use client"` is defined as the first line of code:
```tsx filename="pages/index.tsx" switcher
import Script from 'next/script'
export default function Page() {
return (
)
}
```
```jsx filename="pages/index.js" switcher
import Script from 'next/script'
export default function Page() {
return (
)
}
```
Refer to the [`next/script`](/docs/pages/api-reference/components/script#onload) API reference to learn more about each event handler and view examples.
</PagesOnly>
### Additional Attributes
There are many DOM attributes that can be assigned to a `<script>` element that are not used by the Script component, like [`nonce`](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/nonce) or [custom data attributes](https://developer.mozilla.org/docs/Web/HTML/Global_attributes/data-*). Including any additional attributes will automatically forward it to the final, optimized `<script>` element that is included in the HTML.
<AppOnly>
```tsx filename="app/page.tsx" switcher
import Script from 'next/script'
export default function Page() {
return (
)
}
```
```jsx filename="app/page.js" switcher
import Script from 'next/script'
export default function Page() {
return (
)
}
```
</AppOnly>
<PagesOnly>
```tsx filename="pages/index.tsx" switcher
import Script from 'next/script'
export default function Page() {
return (
)
}
```
```jsx filename="pages/index.js" switcher
import Script from 'next/script'
export default function Page() {
return (
)
}
```
</PagesOnly>
|