我们将 GA 代码添加到 JS 文件并从那里调用它。这是我们在 <head>
中得到的内容标签:
<script src="/public/tail/tail.js"></script>
这是我们目前在 .js 文件中得到的内容:
// Global site tag (gtag.js) - Google Analytics
dynamicLoadJs('https://www.googletagmanager.com/gtag/js?id=UA-74793602-1','async');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-849140015');
gtag('config', 'UA-74793602-1', { 'anonymize_ip': true });
但是,显然有一个问题,几天后,我没有得到统计数据!
有什么我需要更改的想法吗?
最佳答案
dynamicLoadJs
函数对网络进行异步调用以开始下载脚本,但您编写的代码会立即执行,甚至在 JS 文件完成下载之前。
您需要的是在脚本加载和执行后触发的“回调”。
因此您应该有效地拥有如下代码:
/*This function will load script and call the callback once the script has loaded*/
function loadScriptAsync(scriptSrc, callback) {
if (typeof callback !== 'function') {
throw new Error('Not a valid callback for async script load');
}
var script = document.createElement('script');
script.onload = callback;
script.src = scriptSrc;
document.head.appendChild(script);
}
/* This is the part where you call the above defined function and "call back" your code which gets executed after the script has loaded */
loadScriptAsync('https://www.googletagmanager.com/gtag/js?id=UA-74793602-1', function(){
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'AW-849140015');
gtag('config', 'UA-74793602-1', { 'anonymize_ip': true });
})
希望这在概念上也是清晰的。
关于javascript - 将 Google Analytics 代码放入 JS 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51833090/