如何在HTML内联script标签中复用已获取的Google Analytics密钥
实现方案
你没法直接修改硬编码在HTML中的第一个script标签的src属性:浏览器解析HTML时遇到写死的script标签会立刻发起资源请求,此时你的密钥获取逻辑还未执行,根本来不及替换<key here>占位符。你自己尝试的动态创建script标签注入是唯一可行的正确方案,只需要做少量优化即可正常运行:
- 可以省略
type属性,现代浏览器默认script标签类型为text/javascript - 用
document.head替代getElementsByTagName('head')[0],写法更简洁 - 确保代码执行时
#app元素已经渲染完成,建议把这段script放在#app元素的下方,或者包裹在DOMContentLoaded事件回调中,避免获取不到元素报错
基于secret-key场景的完整可运行代码
<div id="app" secret-key="你的GA密钥"></div> <script> document.addEventListener('DOMContentLoaded', function() { const container = document.getElementById('app'); const key = container.getAttribute('secret-key'); // 动态注入gtag脚本 const gaScript = document.createElement('script'); gaScript.async = true; gaScript.src = `https://www.googletagmanager.com/gtag/js?id=${key}`; document.head.appendChild(gaScript); // gtag初始化逻辑 window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', key); }) </script>
基于data-bootstrap配置场景的优化后代码
<script> document.addEventListener('DOMContentLoaded', function() { const container = document.getElementById('app'); const configKeys = JSON.parse(container.getAttribute('data-bootstrap')).common.conf; const gaKey = configKeys['GOOGLE_ANALYTICS_KEY']; // 动态注入gtag脚本 const gaScriptTag = document.createElement('script'); gaScriptTag.async = true; gaScriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${gaKey}`; document.head.appendChild(gaScriptTag); // gtag初始化逻辑 window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', gaKey); }) </script>
内容的提问来源于stack exchange,提问作者user6792790
相关产品推荐
相关产品推荐

