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

查看:20
本文介绍了检查是否加载了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.

有什么想法吗?如果您想知道,并非该站点的所有用户都可以访问 Internet,这就是我提供本地版本的原因.在这种情况下会发生更多事情,例如添加一个 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.

编辑检查用户是否可以访问 Internet 的解决方案也可以.但我还没有找到任何适用于所有现代浏览器的解决方案.

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.

推荐答案

有一个函数可以跟踪库是否已加载.来自 文档:

There's a function to track if the library has loaded. From the docs:

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天全站免登陆