#Move js script from head to body end in page router
1 messages · Page 1 of 1 (latest)
Hi @slim musk. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, you can control the placement of scripts by using the built-in next/script component. However, it's important to note that the next/script component should not be used in a next/head component. Instead, you should move the <Script /> component outside of <Head>.
Here's an example of how you can do this:
Before
import Script from 'next/script'
import Head from 'next/head'
export default function Index() {
return (
<Head>
<title>Next.js</title>
<Script src="/my-script.js" />
</Head>
)
}
After
import Script from 'next/script'
import Head from 'next/head'
export default function Index() {
return (
<>
<Head>
<title>Next.js</title>
</Head>
<Script src="/my-script.js" />
</>
)
}
In the above example, the <Script /> component is moved outside of the <Head> component, which will place the script at the end of the body when the page is rendered.
For more control over the placement of scripts, you can create a custom Document. This allows you to update the <html> and <body> tags used to render a page. Here's an example of how to override the default Document:
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
In the above example, the <NextScript /> component is placed at the end of the <body> tag, which will ensure that all Next.js scripts are loaded at the end of the body.
Please refer to the following documentation for more details:
- No Script Component in Head (https://nextjs.org/docs/messages/no-script-component-in-head)
- Custom Document (https://nextjs.org/docs/pages/building-your-application/routing/custom-document)