添加Google Analytics到Astro 网站

前端112 次阅读7 分钟

1、设置 Google Analytics

访问**Google Analytics**帐户,为自己的网站创建Google Analytics追踪代码。

最终会得到类似如下的代码

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'MEASUREMENT_ID');
</script>

注意:如果你复制上述代码,请确保将这两个MEASUREMENT_ID值替换为你的测量 ID 的实际值。

2、直接集成 GA 代码到Astro

一般将上面的代码添加到网站通用的 标签内即可。具体代码位置看下使用的 Astro 模板,比较可能的一个代码文件在 Layout.astro。

此外放入中的这段追踪代码,还需要添加。

最终的实现将如下:

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"></script>
<script is:inline>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'MEASUREMENT_ID');
</script>

3、借助 Partytown 第三方库

直接集成 GA 代码可能会遇到一些性能问题,另一个方法是借助Partytown 的库。

Partytown 允许集成第三方代码实现同样的功能,而不会降低网站的性能。可以参考在**此处**的文档了解更多相关信息。

3.1 步骤1 - 安装 Partytown 依赖

在 Astro 项目终端运行命令来安装 Partytown:

npm install @astrojs/partytown

3.2 步骤2 - 配置Partytown

安装完成后,将Partytown集成添加到你的astro.config.mjs文件中:

import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import partytown from '@astrojs/partytown'
import sitemap from '@astrojs/sitemap';

// https://astro.build/config
export default defineConfig({
    site: 'https://astro-article.netlify.app/',
    integrations: [
        mdx(), 
        sitemap(),
        partytown({
            config: {
              forward: ["dataLayer.push"],
            },
        }),
    ],
});

在上面的代码中,我们导入了 Partytown 库:**import partytown from '@astrojs/partytown'**。 然后我们将这段代码添加到integrations对象中。

3.3 步骤3 - 添加 GA 代码

将 Google Analytics代码添加到页面

<!-- Google tag (gtag.js) -->
<script type="text/partytown" async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"></script>
<script type="text/partytown">
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'MEASUREMENT_ID');
</script>

同样上面的代码添加到网站通用的 标签内。具体代码位置看下使用的 Astro 模板,比较可能的一个代码文件在 Layout.astro。

注意:

我们type=“text/partytown”向两个

3.4 步骤4 - 构建部署

构建并部署你的项目

比如使用npm run build其构建到dist文件夹中,然后将代码推送到 GitHub。这会自动触发 Netlify 部署。

网站部署完成后,需要等待一段时间才能在 Google Analytics 信息中心中查看分析结果。

继续阅读

基于全文检索与主题相似度