You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Astro框架下Google Tag Manager脚本未在页面源码显示的问题

Astro中内Google Tag Manager脚本消失的问题解决

问题描述

我在使用Astro框架构建静态页面时,按要求在<head>标签开头添加了Google Tag Manager(GTM)脚本,并在<body>标签开头添加了对应的noscript标签(代码如下)。但<head>顶部的GTM脚本在页面源码和浏览器检查元素中完全不可见,仅能看到脚本前后的注释;而<body>顶部的noscript标签显示正常。

Invisible Google Tag

代码示例

---
import Footer from "../components/SharedComponents/Footer.astro";
import Hero, { TypeOfHeroContent } from "../components/SharedComponents/Hero.astro";
import Navbar from "../components/SharedComponents/Navbar.astro";
import { networksAndHero } from "../components/SharedComponents/NetworksAndHeroPreload.astro";

export interface Props {
  title?: string;
  description?: string;
  keywords?: string;
  heroContentType?: TypeOfHeroContent;
  navbarColor?: string;
  pageName?: string;
}

const { title, description, keywords, heroContentType, navbarColor, pageName } = Astro.props;
---

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Google Tag Manager -->
    <script>
      (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-PCP4MNJ");
    </script>
    <!-- End Google Tag Manager -->
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <link rel="icon" type="image/svg+xml" href="/assets/favicon.ico" />
    <link rel="sitemap" href="/sitemap-index.xml" />
    <link rel="preload" href="/fonts/Inter.var.woff2" as="font" type="font/woff2" crossorigin />
    {
      networksAndHero.map((images) => (
        <link rel="preload" as="image" href={images.img} type="image/webp" />
      ))
    }
    <meta
      name="robots"
      content="follow, index, max-snippet:-1, max-video-preview:-1, max-image-preview:large"
    />
    <meta name="generator" content={Astro.generator} />
    <meta name="description" content={description} />
    <meta name="keywords" content={keywords} />
    <title>{title}</title>
    <style>
      img {
        aspect-ratio: attr(width) / attr(height);
        height: auto;
        max-width: 100%;
      }
      @font-face {
        font-family: "inter";
        src: url("/fonts/Inter.var.woff2") format("woff2");
        font-display: block;
      }
    </style>
  </head>

  <body class="bg-fieldblack font-sans">
    <!-- Google Tag Manager (noscript) -->
    <noscript>
      <iframe
        src="https://www.googletagmanager.com/ns.html?id=GTM-PCP4MNJ"
        height="0"
        width="0"
        style="display:none;visibility:hidden"
      >
      </iframe>
    </noscript>
    <!-- End Google Tag Manager (noscript) -->
    <Navbar navbarColor={navbarColor} />
    {heroContentType && <Hero heroContentType={heroContentType} />}
    <slot />
    <Footer pageName={pageName} />
  </body>
</html>

解决方案

  • 添加is:inline指令强制保留脚本位置
    Astro默认会优化内联脚本,可能将其移至页面底部或打包处理。给GTM脚本添加is:inline属性,告诉Astro不修改该脚本的位置:
<script is:inline>
  (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-PCP4MNJ");
</script>
  • 升级Astro到最新稳定版
    旧版本Astro可能存在内联脚本渲染的bug,执行以下命令升级:
npm install astro@latest
  • 检查第三方插件干扰
    如果使用了@astrojs/partytown等脚本管理插件,它们可能自动迁移GTM脚本到后台运行,导致源码中不可见。可以暂时禁用这类插件,验证脚本是否正常显示。

  • 验证生产构建结果
    开发服务器的实时预览可能存在缓存问题,执行生产构建后查看dist目录下的静态文件:

npm run build

若构建后的HTML中存在脚本,说明是开发服务器的临时问题;若仍不存在,继续排查astro.config.mjs中的优化配置。

内容的提问来源于stack exchange,提问作者rectangular_circle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 04:47:32