Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Google Analytics goes down, how do I keep my site working?

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.

Here's a few screenshots of what happens

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.

enter image description here

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.

enter image description here

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. Is there's a timeout I can add to my script that will cancel the connection to Google Analytics and halt the request/download if it's taking too long? Then it would continue loading my site after 2 seconds.
  2. Or better yet, perhaps it can just load my site completely, then send a request off to Google Analytics using Ajax after my site is completely finished loading? Why doesn't it do this by default?

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>

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.

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?

Many thanks

Solution Update

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>

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.

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

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.

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.

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.

like image 846
zuallauz Avatar asked Jan 19 '13 10:01

zuallauz


People also ask

Does Google Analytics work if cookies are blocked?

Since Google Analytics uses cookies to identify users and their actions and attributes, this means that if a user opts-out of cookies entirely, they won't be tracked as a visitor at all through your analytics. This could cause a decrease in measurable website traffic depending on how many visitors choose to opt in.

Is Google Analytics slowing down a website?

No, adding Google Analytics will not slow down your website. Google Analytics is a lightweight script that doesn't require a lot of resources to run. In fact, it can actually help speed up your website by loading asynchronously. How do I get Google analytics for my website?


2 Answers

Given where it's loaded, the rest of your site would load before the request to Google Analytics. Plus GA is loaded asynchronously, not halting the execution of any of your code, so I really don't see there being an issue.

like image 166
sevenseacat Avatar answered Oct 26 '22 02:10

sevenseacat


Latest Approach :

  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>
    

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

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>

Hope this helps

like image 21
2 revs Avatar answered Oct 26 '22 03:10

2 revs