Javascript 将Google分析代码放入JS文件中

Javascript 将Google分析代码放入JS文件中,javascript,google-analytics,Javascript,Google Analytics,我们将GA代码添加到JS文件中,并从那里调用它。下面是我们在标签中得到的内容: <script src="/public/tail/tail.js"></script> 然而,这显然是一个问题,因为几天后,我无法获得统计数据 知道我需要更改什么吗?函数dynamicLoadJs对网络进行异步调用以开始下载脚本,但是您编写的代码会立即执行,甚至在JS文件完成下载之前 您需要的是一个“回调”,它在加载并执行脚本后被触发 因此,您应该有效地拥有如下代码: /*This fun

我们将GA代码添加到JS文件中,并从那里调用它。下面是我们在
标签中得到的内容:

<script src="/public/tail/tail.js"></script>
然而,这显然是一个问题,因为几天后,我无法获得统计数据


知道我需要更改什么吗?

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

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

dynamicLoadJs
”和“
async
”让我相信您可能在加载文件之前调用了
gtag
。您是否在控制台中看到错误?非常感谢,非常感谢您的帮助@乔治,嘿,对你有用吗?渴望知道。:)实际上,你可以在谷歌分析“实时”部分查看用户的实时点击量。@Sponge先生,我怎样才能把它作为一个公认的答案呢?有没有扣子或什么东西我没扣?
/*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 });
})