docs: Updates "No Before Interactive" error message for App router (#56033)

Co-authored-by: Lee Robinson <me@leerob.io>
This commit is contained in:
Michael Novotny 2023-12-27 10:54:17 -06:00 committed by GitHub
parent 332bf6d4f8
commit 7e00d1871c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -2,15 +2,37 @@
title: No Before Interactive Script Outside Document title: No Before Interactive Script Outside Document
--- ---
> Prevent usage of `next/script`'s `beforeInteractive` strategy outside of `pages/_document.js`. > Prevent usage of `next/script`'s `beforeInteractive` strategy outside of `app/layout.jsx` or `pages/_document.js`.
## Why This Error Occurred ## Why This Error Occurred
You cannot use the `next/script` component with the `beforeInteractive` strategy outside `pages/_document.js`. That's because `beforeInteractive` strategy only works inside **`pages/_document.js`** and is 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). You cannot use the `next/script` component with the `beforeInteractive` strategy outside `app/layout.jsx` or `pages/_document.js`. That's because `beforeInteractive` strategy only works inside **`app/layout.jsx`** or **`pages/_document.js`** and is 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).
## Possible Ways to Fix It ## Possible Ways to Fix It
If you want a global script, move the script inside `pages/_document.js`. ### App Router
If you want a global script, and you are using the App Router, move the script inside `app/layout.jsx`.
```jsx filename="app/layout.jsx"
import Script from 'next/script'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
<Script
src="https://example.com/script.js"
strategy="beforeInteractive"
/>
</html>
)
}
```
### Pages Router
If you want a global script, and you are using the Pages Router, move the script inside `pages/_document.js`.
```jsx filename="pages/_document.js" ```jsx filename="pages/_document.js"
import { Html, Head, Main, NextScript } from 'next/document' import { Html, Head, Main, NextScript } from 'next/document'
@ -24,7 +46,7 @@ export default function Document() {
<Main /> <Main />
<NextScript /> <NextScript />
<Script <Script
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" src="https://example.com/script.js"
strategy="beforeInteractive" strategy="beforeInteractive"
></Script> ></Script>
</body> </body>
@ -33,4 +55,5 @@ export default function Document() {
} }
``` ```
- [next-script](/docs/pages/building-your-application/optimizing/scripts) - [App Router Script Optimization](/docs/app/building-your-application/optimizing/scripts)
- [Pages Router Script Optimization](/docs/pages/building-your-application/optimizing/scripts)