如何使用 next/script 组件 (Next.js 11) 加载 Google 跟踪代码管理器?

fel*_*osh 18 javascript google-tag-manager next.js

ScriptNext.js v11 发布了一个具有不同策略的新组件。

建议加载带afterInteractive策略的 Google TagManager。

我试过了

// _app.js

import Script from 'next/script';

class MyApp extends App {
  public render() {
    const { Component, pageProps } = this.props;

    return (
      <>
        <Script strategy="afterInteractive">
          {`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':` +
            `new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],` +
            `j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=` +
            `'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);` +
            `})(window,document,'script','dataLayer','GTM-XXXXXXX');`}
        </Script>
        <Component {...pageProps} />
      </>
    );
  }
}

export default MyApp;
Run Code Online (Sandbox Code Playgroud)

它工作正常,它加载谷歌标签管理器,但问题是它在每个页面导航上注入相同的脚本,这会产生重复的标签。

如何使用新Script组件?

Ste*_*e L 18

id您必须为组件设置 an ,<Script>因为它具有内联内容(无src属性)。

接下来可以检查它是否已经渲染,并且您不会有这些重复。

这是与 Next 关联的 eslint 规则:

具有内联内容的 next/script 组件需要定义 id 属性来跟踪和优化脚本。

请参阅: https: //nextjs.org/docs/messages/inline-script-id

所以你的解决方案可能是:

    <Script id="gtm-script" strategy="afterInteractive">{`...`}</Script>
Run Code Online (Sandbox Code Playgroud)

您可能还应该为您的下一个项目安装 eslint:
运行next lint或安装 eslint next config:

yarn add -D eslint eslint-config-next
Run Code Online (Sandbox Code Playgroud)

并至少使用以下内容定义文件 .eslintrc.json :

{
  "extends": ["next/core-web-vitals"]
}
Run Code Online (Sandbox Code Playgroud)

有关 next.js eslint 配置的信息。

  • 是的,这是专门针对内联脚本的,因为在这种情况下您没有“src”属性。 (2认同)

fel*_*osh 9

我最终的解决方案是分解 GTM 脚本。

将初始dataLayer对象放置在页面窗口上_document

// _document.js

import Document, { Head, Html, Main, NextScript } from 'next/document';

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          <meta charSet="utf-8" />

          <script
            dangerouslySetInnerHTML={{
              __html:
                `(function(w,l){` +
                `w[l] = w[l] || [];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});` +
                `})(window,'dataLayer');`,
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

使用组件加载GMT脚本Script(页面中不允许使用_document

// _app.js

import Script from 'next/script';

class MyApp extends App {
  public render() {
    const { Component, pageProps } = this.props;

    return (
      <>
        <Script src={`https://www.googletagmanager.com/gtm.js?id=GMT-XXXXXXX`} />
        <Component {...pageProps} />
      </>
    );
  }
}

export default MyApp;
Run Code Online (Sandbox Code Playgroud)