从这个答案和这篇文章中,我已经添加了一个<Script>
来将Google Tag Manager添加到我的NextJS网站中:
components/layout.tsx:
import React from "react";
import Head from "next/head";
import Script from 'next/script'
<!-- skip some code -->
<Head>
<link rel="preconnect" href="https://cdn.sanity.io/" />
<link rel="dns-prefetch" href="https://cdn.sanity.io//" />
</Head>
<Script id="google-tag-manager" 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=%27+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-xxxx');
}
</Script>
然而,该脚本在前端不存在。
components/layout.tsx
是我网站上唯一带有 <Head>
或 <head>
的文件。
Google Tag Manager <noscript>
存在于前端,在 app/layout.tsx:
中使用。
<body className="antialiased text-gray-800 dark:bg-black dark:text-gray-400">
<noscript
dangerouslySetInnerHTML={{
__html: <iframe src="https://www.googletagmanager.com/ns.html?id=xxxx" height="0" width="0" style="display: none; visibility: hidden;" />,
}}
/>
所以我知道我已经保存了所有更改。
感谢您的帮助。
更新
我是NextJS的新手,所有这些代码都来自于一个NextJS / Sanity模板,它在本地和Vercel暂存站点上都可以正常工作。
我的唯一问题是在发布到我的域之前无法正确加载Google Tag Manager。
项目中没有_app.js
。
有/app/(website)/layout.tsx
:
import "@/styles/tailwind.css";
import { Providers } from "./providers";
import { cx } from "@/utils/all";
import { Inter, Lora } from "next/font/google";
const inter = Inter({
subsets: ["latin"],
variable: "--font-inter"
});
const lora = Lora({
subsets: ["latin"],
variable: "--font-lora"
});
export default function RootLayout({
children
}: {
children: React.ReactNode;
}) {
return (
<html
lang="en"
suppressHydrationWarning
className={cx(inter.variable, lora.variable)}>
<body className="antialiased text-gray-800 dark:bg-black dark:text-gray-400" >
<noscript
dangerouslySetInnerHTML={{
__html: `<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-xxxx" height="0" width="0" style="display: none; visibility: hidden;" />`,
}}
/>
<Providers>{children}</Providers>
</body>
</html>
);
}
这是 /app/(website)/providers.tsx
文件:
"use client";
import { ThemeProvider } from "next-themes";
export function Providers({ children }) {
return (
<ThemeProvider attribute="class" defaultTheme="light">
{children}
</ThemeProvider>
);
}
如果我在VSCode中搜索RootLayout
,没有任何调用它的内容,所以我有点困惑哪个是主文件。
如果您想要访问Github存储库,我可以提供它。