![](/img/trans.png)
[英]How to add <script> js include to the closing </body> tag in React?
[英]How to add third party script after closing body tag for certain pages only in NextJS
我有一个 NextJS 应用程序,其中只在某些页面上需要第三方脚本。 目前它正在所有页面上触发,但这会导致一些问题。
它目前通过自定义_document.js
文件添加在结束body
标记之后。 由于脚本的主体必须为 go,因此我无法在 NextJS 中使用head
选项。
仅在特定页面模板上触发的最佳方法是什么?
import { Html, Head, Main, NextScript } from 'next/document';
import Script from 'next/script';
export default function Document() {
return (
<Html>
<Head></Head>
<body>
<Main />
<NextScript />
{/** Below script only needed on certain pages */}
<script
src="xxx"
id="widget"
/>
</body>
</Html>
)
}
您应该改为在_app.js
中执行此操作:
import Script from 'next/script'
const allowedPages = new Set([...]);
export default function MyApp({ Component, pageProps }) {
const { asPath } = useRouter();
const enableScript = allowedPages.has(asPath);
return (
<>
<Component {...pageProps} />
{enableScript && <Script id="widget" src="xxx" />}
</>
)
}
因为您将有权访问useRouter
并且它会在每次页面导航时更新。 _document.js
仅在第一个SSR 上使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.