javascript - 如果 Google Analytics 出现故障,我该如何保持我的网站正常运行?

标签 javascript jquery ajax asynchronous google-analytics

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

以下是发生的一些截图

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

enter image description here

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

enter image description here

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

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

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

  • 这是我们必须使用的代码,当前插入在关闭 </body> 标记之前。
    <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。

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

    非常感谢

    解决方案更新

    好的,我已经在 J​​aspal 的帮助下找到了有效的方法。解决方法如下。
    <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,但我仍然没有获得任何浏览器视觉效果 - 完美。

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

    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 超时。无论如何,我并不担心,因为它会静默超时并且用户不会注意到,因为浏览器中没有加载视觉效果。

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

    最佳答案

    最新方法:

  • 我们允许 ga 正常加载。
  • 我们将 ga dom 元素的引用存储在全局变量 (gaClone) 中。
  • 我们将超时设置为 30 秒。我们还设置了另一个全局变量 (loadedGoogleAnalytics) 并最初将其设置为 0。当 ga 加载时,我们将此变量设置为 1。在超时到期时,我们检查 ga 是否已加载。如果没有,我们删除dom元素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 帐户验证了这种方法,我能够看到所有实时跟踪]

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

    希望这可以帮助

    关于javascript - 如果 Google Analytics 出现故障,我该如何保持我的网站正常运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14413271/

    相关文章:

    javascript - 返回一个表示图像为 JSON 的 byte[]?

    javascript - passport.js + express : TypeError ('Router.use() requires a middleware function but got a ' + gettype(fn))

    javascript - AngularJs 选择图表框架 d3.js 与 highcharts

    javascript - 我似乎无法发布一系列对象

    javascript - 需要帮助了解 Ajax 功能

    javascript - 将html代码返回给jquery好不好?

    javascript - Chartjs - 将附加数据插入图表工具提示

    javascript - 谷歌地图 : Issue regarding marker icons and geocoding

    javascript - .click() 的原始 Javascript 版本

    javascript - Javascript 库应该动态添加依赖项吗?