如何用JS在非Googlebot用户代理时向head中添加Google Analytics代码
解决非Googlebot用户加载Google Analytics的问题
你的核心需求是仅当访问者不是Googlebot时,才在页面head中加载Google Analytics脚本,但当前代码存在关键问题:直接将脚本字符串通过prepend插入head,浏览器会把它当作普通文本处理,不会执行脚本逻辑。以下是修正后的实现方案:
修正后的代码
<script type="text/javascript"> var agent = navigator.userAgent.toLowerCase(); // 检测是否为Googlebot var isGooglebot = agent.includes('googlebot'); if (!isGooglebot) { // 加载gtag.js外部脚本 var gtagScript = document.createElement('script'); gtagScript.async = true; gtagScript.src = 'https://www.googletagmanager.com/gtag/js?id=UA-123456789-1'; document.head.appendChild(gtagScript); // 加载GA配置内联脚本 var configScript = document.createElement('script'); configScript.textContent = ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-123456789-1'); `; document.head.appendChild(configScript); } </script>
关键修正点说明
- 替换字符串插入为动态创建script元素:通过
document.createElement('script')生成标准脚本元素,设置对应属性后插入head,浏览器会正常识别并执行脚本。 - 简化UA检测逻辑:用
includes替代match,更简洁直观,同样能准确判断UserAgent是否包含Googlebot标识。 - 分离GA脚本逻辑:分别处理外部资源脚本(gtag.js)和内联配置脚本,确保加载顺序和执行逻辑符合GA的要求。
额外注意事项
- 这段代码建议放在页面
</head>标签之前,确保脚本能及时插入head中执行。 - 如果需要兼容更老的浏览器,可以把模板字符串换成普通字符串拼接(注意转义内部单引号)。
内容的提问来源于stack exchange,提问作者Witcher
相关产品推荐
相关产品推荐

