检查analytics.js是否已加载 [英] Check if analytics.js is loaded

查看:78
本文介绍了检查analytics.js是否已加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用我的服务器提供的本地analytics.js。我只想在必要时使用本地版本 - 那么是否有解决方案来检查analytics.js的调用是否失败?

I have to use a local analytics.js that I serve from my server. I just want to use the local version if necessary - so is there a solution for checking if the call for analytics.js has failed?

我想过用全局window.onerror,但我不认为失败的外部文件调用会导致错误。我尝试检查ga()是否可用,但即使analytics.js未加载,也是如此。

I thought about checking it with a global window.onerror, but I don't think a failed call for an external file causes an error. I've tried checking if ga() is available, but it is even if analytics.js isn't loaded.

有什么想法?如果您想知道,并非本网站的所有用户都可以访问互联网,那就是我服务本地版本的原因。在这种情况下会发生更多事情,例如添加sendHitTask以将答案从analytics.js重定向到本地服务器。

Any ideas? If you are wondering, not all users of this site has internet access, that's why I'm serving a local version. There is more things happening in this case, like adding a sendHitTask to redirect the answer from analytics.js to the local server.

编辑
您检查用户是否可以上网的解决方案也可以。但我还没有找到任何解决方案,这可以适用于所有现代浏览器。

EDIT A solution where you check if the user has Internet access would also be OK. But I have not found any solution for this either that works on all modern browsers.

推荐答案

有一个函数来跟踪库已加载。从文档 https://developers.google。 com / analytics / devguides / collection / analyticsjs / command-queue-reference#ready-callback

There's a function to track if the library has loaded. From the docs https://developers.google.com/analytics/devguides/collection/analyticsjs/command-queue-reference#ready-callback:

ga(function(tracker) {
   var defaultPage = tracker.get('page');
});

传入函数在加载库时执行,因此您可以设置一个变量来跟踪是否已加载。你必须把它放在某种计时器上,以决定你何时考虑失败:

The passed in function is executed when the library is loaded, so you could set a variable to keep track of whether or not it has loaded. You'd have to put it on some sort of timer to decide when you want to consider it failed:

var loaded = false;
ga(function() {
   loaded = true;
});

// after one second do something if the library hasn't loaded
setTimeout(function(){
    if (!loaded){
        //do something
    }
},1000);

这篇关于检查analytics.js是否已加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆