如何使用 next/script 组件(Next.js 11)加载谷歌标签管理器? [英] How to load Google Tag Manager with next/script component (Next.js 11)?
问题描述
Next.js v11 发布了一个新的 Script
组件有不同的策略.
Next.js v11 released a new Script
component which has different strategies.
建议使用 afterInteractive
策略加载 Google TagManager.
It is recommended to load Google TagManager with afterInteractive
strategy.
我试过了
// _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;
它工作正常,它加载谷歌标签管理器,但问题是它在每个页面导航上注入相同的脚本,这会产生重复的标签.
It works fine, it loads google tag manager, but the problem is that it injects the same script on every page nav, which makes duplicate tags.
如何使用新的Script
组件?
推荐答案
我的最终解决方案是拆分 GTM 脚本.
My final solution was to break apart the GTM script.
将初始dataLayer
对象放在_document
页面的窗口中.
Putting the initial dataLayer
object on the window in _document
page.
// _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>
);
}
}
用Script
组件加载GMT脚本(_document
页面中不允许使用)
Loading the GMT script with Script
component (which is not allowed to be used in the _document
page)
// _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;
这篇关于如何使用 next/script 组件(Next.js 11)加载谷歌标签管理器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!