繁体   English   中英

如何仅在 NextJS 中为某些页面关闭 body 标记后添加第三方脚本

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM