<script async src="https://www.googletagmanager.com/gtag/js?id=<key here>"></script>
<script>
const container = document.getElementById('app');
const key = container.getAttribute('secret-key');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', key);
</script>
我正在嘗試訪問我需要在<script>標簽中添加 Google Analytics 的密鑰。我能夠在第二個代碼塊中使用
const container = document.getElementById('app');
const key = container.getAttribute('secret-key');
我想對第一個<script>子句使用相同的鍵,但我不確定是否可以對 inline 做同樣的事情<script>?我想用它const key來替換<key here>.
我怎樣才能做到這一點?
編輯
<script>
function appendGAScriptTag() {
const configKeys = JSON.parse(container.getAttribute('data-bootstrap')).common.conf;
const gaKey = configKeys['GOOGLE_ANALYTICS_KEY'];
let gaScriptTag = document.createElement('script');
gaScriptTag.type = 'text/javascript';
gaScriptTag.async = true;
gaScriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${gaKey}`;
document.getElementsByTagName('head')[0].appendChild(gaScriptTag);
}
appendGAScriptTag(); // <--- calling it here
</script>
uj5u.com熱心網友回復:
您可以<script>使用……更多 JavaScript動態創建標簽!
function appendGAScriptTag() {
var gaScriptTag = document.createElement('script');
gaScriptTag.type = 'text/javascript';
gaScriptTag.async = true;
gaScriptTag.src = `https://www.googletagmanager.com/gtag/js?id=${document.getElementById('app').getAttribute('secret-key')}`;
document.getElementsByTagName('head')[0].appendChild(gaScriptTag);
}
appendGAScriptTag()當您想要將生成的元素注入到 DOM 中時,請呼叫您預先存在的 JavaScript 代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370134.html
標籤:javascript html 谷歌分析
上一篇:重繪后反應Redux和狀態
