将Google Analytics(分析)代码放入JS文件中

时间:2018-08-14 02:57:16

标签: javascript google-analytics

我们将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 });

但是,显然存在问题,几天后,我无法获得统计信息!

有什么想法需要改变吗?

1 个答案:

答案 0 :(得分:1)

函数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 });
})

希望这在概念上也很清楚。