如果 Google Analytics 出现故障,我该如何保持我的网站正常运行? [英] If Google Analytics goes down, how do I keep my site working?

查看:25
本文介绍了如果 Google Analytics 出现故障,我该如何保持我的网站正常运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,现在是 2013 年 1 月 19 日 22:30 NZST,由于 Google Analytics 的运行速度似乎非常缓慢,因此大部分互联网似乎都在爬行.Stackoverflow、Firefox.com、reddit 和 google 搜索都很慢.对我来说最重要的是,我的生产业务网站运行缓慢或根本无法加载.不,这不仅仅是我的连接我也在我的手机上用 3G 测试过.没有 Google Analytics(分析)的网站似乎运行良好.

Ok it's 19 Jan 2013 22:30 NZST and most of the internet seems to have come to a crawl as Google Analytics seems to be running really slow. Stackoverflow, Firefox.com, reddit and google searches are slow. Most importantly for me, my production business website is running slow or not loading at all. No it's not just my connection I tested it on my phone with 3G as well. Sites without Google Analytics seemed to be running fine.

这是发生的一些屏幕截图

它位于 Firefox 窗口的左下角.它会像那样坐在那里超过 20 秒.如果无法连接,我希望它在 3 秒后消失.

This is in the bottom left corner of the Firefox window. It will sit there for 20+ seconds like that. I'd like it to go away after 3 seconds if it can't connect.

这个旋转的绿色图像位于 Firefox 选项卡中,只是坐在那里,看起来页面仍在加载 20 多秒.如果无法连接,我希望它在 3 秒后消失.

This spinning green image is in the Firefox tab and just sits there making it look like the page is still loading for 20+ seconds. I'd like it to go away after 3 seconds if it can't connect.

现在可能不是谷歌分析,我国家的国际网关可能运行缓慢什么的.但证据强烈表明它可能是谷歌分析.现在,即使它不是 Google Analytics,如果服务完全关闭,我仍然会对某些方法感兴趣.因此,假设 Google Analytics 的数据中心发生了一场大火,并且灭火系统出现故障.现在 Google Analytics 会完全脱机几天.没有备份服务器.没有备用数据中心.假设场景还可以.现在我的网站仍然需要运行,因为我不能让我的网站依赖于 Google Analytics 服务.但是,如果服务真正及时运行,分析功能将是一个很好的额外奖励.

Now it may not be Google Analytics, my country' international gateway may be running slow or something. But evidence strongly suggests it might be Google Analytics. Now even if it isn't Google Analytics then I'd still be interested in some methods to counter it if the service is completely down. So hypothetically lets assume there's a massive fire at the datacenter of Google Analytics and the fire suppression systems failed. Now Google Analytics goes completely offline for several days. No backup servers. No standby datacenters. Hypothetical scenario ok. Now my site still needs to run as I can't afford to have my site reliant on Google Analytics service being up. But the analytics functionality would be good to have as an added bonus if the service is actually running in a timely manner.

好的,所以我在这里抛出一些想法:

Ok so I'm throwing out some ideas here:

  1. 是否可以将超时添加到我的脚本中,以取消与 Google Analytics(分析)的连接并在时间过长时停止请求/下载?然后它会在 2 秒后继续加载我的网站.
  2. 或者更好的是,也许它可以完全加载我的网站,然后在我的网站完全加载完成后使用 Ajax 向 Google Analytics 发送请求?为什么默认情况下不这样做?

这是我们必须使用的代码,当前插入在结束 </body> 标记之前.

Here's the code we have to work with which is currently inserted just before the closing </body> tag.

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-123456789-1']);
    _gaq.push(['_trackPageview']);
    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

现在,我可以采用哪些方法来解决这个假设的灾难场景,并在 Google Analytics 关闭时让我的网站保持连续性?我对潜在的软件或硬件解决方案感兴趣.假设我可以完全访问运行我的 PHP/MySQL/HTML5 网站的 Linux VPS.

Now, what are some methods I could employ that would fix this hypothetical disaster scenario and give my website continuity while Google Analytics is down? I'm interested in either potential software or hardware solutions. Assume I have full access to a Linux VPS which my PHP/MySQL/HTML5 website is running on.

另外,对此的权威答案是什么:有些人说将代码放在结束 </head> 标记之前.其他人说把它放在结束 </body> 标签之前.哪种方式最好?

Also, what's the authoritative answer on this: some people say place the code before the closing </head> tag. Others say place it before the closing </body> tag. Which is the best way?

非常感谢

解决方案更新

好的,我已经在 J​​aspal 的帮助下找到了有效的方法.解决方法如下.

Ok I've found out what works with help from Jaspal. The solution is below.

<script type="text/javascript">
    // Load Google Analytics after my site has completely loaded
    // Then when Google Analytics request is made it won't show any visuals in the browser
    setTimeout(loadGoogleAnalytics, 5000);

    // Setup _gaq array as global so that the code in the ga.js file can access it
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-123456789-1']);
    _gaq.push(['_trackPageview']);

    /**
     * Loads Google Analytics
     */
    function loadGoogleAnalytics()
    {
        var srcUrl = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

        $.ajax(
        {
            url: srcUrl,
            cache: true,
            dataType: "script",
            success: function(data)
            {
                console.log('got the script');
            },
            error: function()
            {
                console.log('failed to get the script');
            },
            timeout: 5000
        });
    };
</script>

基本上它为什么起作用是因为有一个 5 秒的 setTimeout.这为我的页面提供了足够的时间来加载所有内容、JS、CSS、图像等.然后它启动 $.ajax 请求并下载 ga.js 和 __utm.gif,这实际上将数据发送到 Google Analytics.在最初的 5 秒之后,基本上我之前提到的所有浏览器视觉效果都消失了,并且 Google Analytics 请求在后台静默发生,浏览器用户没有加载视觉效果.然后我尝试使用主机文件阻止 Google Analytics,但我仍然没有获得任何浏览器视觉效果 - 完美.

Basically why it works is because there is a setTimeout for 5 seconds. This gives my page enough time to load all the content, JS, CSS, images etc. Then after that it kicks off the $.ajax request and downloads ga.js and __utm.gif which is actually sending the data to Google Analytics. After that initial 5 seconds, basically all the browser visuals I mentioned earlier disappear and the Google Analytics request happens silently in the background with no loading visuals for the browser user. Then I tried blocking Google Analytics with the host file and I still don't get any browser visuals - perfect.

需要注意的是$中的timeout: 5000属性.ajax 请求似乎没有做任何事情.最初我希望它会在 5 秒内无法获取数据时中止请求,但 API 文档中有一条注释说

It should be noted that the timeout: 5000 property in the $.ajax request doesn't appear to do anything. Originally I was hoping it would abort the request if it couldn't get data for 5 seconds but there's a note in the API docs saying

仅在 Firefox 3.0+ 中,无法取消脚本和 JSONP 请求超时;即使脚本在超时后到达,脚本也会运行期间.

In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

无论如何我都会把它留在那里以防万一.根据我的测试,如果无法访问 Google Analytics(通过观察 Firebug/Chrome 中的网络/网络面板),那么它将在 Firefox 中 21-23 秒和 Chrome 中 16 秒后中止请求.这可能是一些 TCP 超时.无论如何,我并不担心,因为它会静默超时,用户不会注意到,因为浏览器中没有加载视觉效果.

I'll leave it in there anyway just in case. From my testing if Google Analytics can't be reached (from observing the Net/Network panel in Firebug/Chrome) then it will abort the request after 21-23 seconds in Firefox and 16 seconds in Chrome. This may be some TCP timeout. I'm not worried about that anyway as it's timing out silently and the user will not notice as there's no loading visuals in the browser.

我在下面接受了 Jaspal 的回答并奖励了他,因为他的解决方案对于解决这个问题至关重要.然而,他的解决方案仍然在浏览器中显示加载视觉效果.所以我相信这里发布的使用 setTimeout 的解决方案(对他的原始解决方案略有修改)是可行的方法,并且经过测试可以 100% 为我工作.

I have accepted Jaspal's answer below and awarded him the bounty as his solution was critical to solving this. However his solution still has loading visuals appearing in the browser. So I believe the solution posted here using the setTimeout (a slight modification on his original one) is the way to go and is tested to be working 100% for me.

推荐答案

最新方法:

  1. 我们允许 ga 正常加载.
  2. 我们将 ga dom 元素的引用存储在全局变量 (gaClone) 中.
  3. 我们将超时设置为 30 秒.我们还设置了另一个全局变量 (loadedGoogleAnalytics) 并最初将其设置为 0.当 ga 加载时,我们将此变量设置为 1.在超时到期时,我们检查 ga 是否已加载.如果不是,我们删除dom元素ga.

  1. We allow ga to load normally.
  2. We store a reference to ga dom element in a global variable (gaClone).
  3. We set a timeout of 30seconds. We also set another global variable (loadedGoogleAnalytics) and set it to 0 initially. When ga loads, we set this variable to 1. On the timeout expiry, we check whether ga was loaded or not. If not, we delete the dom element ga.

<script type="text/javascript">
    var loadedGoogleAnalytics = 0;
    var gaClone;
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-123456789-1']);
    _gaq.push(['_trackPageview']);

    _gaq.push(function() {
        loadedGoogleAnalytics = 1;
        //console.log('GA Actualy executed!');
    });

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

        gaClone = ga;

    })();

    setTimeout(function() {
        //console.log('timeout fired');
        if (loadedGoogleAnalytics != 1) {
            gaClone.parentNode.removeChild(gaClone); 
        }
    }, 30000);
</script>

[我已经用我的一个实际 GA 帐户验证了这种方法,我能够看到所有实时跟踪]

[I have verified this approach with one of my actual GA accounts and i am able to see all the realtime tracking]

以前的方法[注意:如果我们尝试将它放在 (document).ready(); 中,Ga 不会执行][此解决方案不起作用]

Previous Approach [Note: Ga does not execute if we try to place it in (document).ready();] [This solution does not work]

<script type="text/javascript">
    $(document).ready(function() {
            var _gaq = _gaq || [];
            _gaq.push(['_setAccount', 'UA-123456789-1']);
            _gaq.push(['_trackPageview']);

            srcUrl = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

            $.ajax({
                url: srcUrl,
                cache: true,
                dataType: "script",
                success: function(data) {
                    //console.log('got the script');
                },
                error: function() {
                    //console.log('failed to get the script');
                },
                timeout: 30000
            });
        });
</script>

希望能帮到你

这篇关于如果 Google Analytics 出现故障,我该如何保持我的网站正常运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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