【发布时间】:2022-01-09 17:03:41
【问题描述】:
我读过How to load Google Tag Manager with next/script component (Next.js 11)?,也读过this doc page。
但他们都没有解决我的问题。
我想在我使用 nextjs 开发的许多网站上包含 Google 标记。因此,我创建了一个简单的可重用组件:
import Script from 'next/script'
const GoogleTag = ({ identifier }) => {
if (!identifier || !identifier.startsWith('G-')) {
throw new Error('Google tag id is not correct;');
}
return <>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${identifier}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${identifier}');
`}
</Script>
</>
}
export default GoogleTag;
我在我的每个站点中使用它,在 _app.js 文件中,这样:
import Head from 'next/head';
import GoogleTag from '../Base/GoogleTag';
export default function MyApp({ Component, pageProps }) {
return (
<>
<Head>
<GoogleTag identifier='G-9XLT855ZE0' />
</Head>
<div>
application code comes here
</div>
</>
)
}
但我没有看到在 Chrom 的开发工具的 int Networks 选项卡中加载了 Google Tag 脚本。
【问题讨论】:
-
next/script不应在next/head内使用。
标签: javascript next.js