views:

21

answers:

1

After reading a blog post, I got the idea to add safety code to ensure that the Google Analytics objects are fully loaded before calling it's functions.

Typicle Google Analytics code goes something like:

var pageTracker = _gat._getTracker("X-UAXXXXX");
pageTracker._trackPageview();

and

pageTracker._addItem( bla bla );
pageTracker._trackTrans();

I have thought of two options to double ensure that the _gat-object is loaded before use:

1) Use JQuery.ready to call the _get-functions. Something like:

$(document).ready(function() {
    var pageTracker = _gat._getTracker("X-UAXXXXX");
    pageTracker._trackPageview();
}

or

2) Use JavaScript timeout

function checkGat() {

    if( gat_is_ready ) {
        var pageTracker = _gat._getTracker("X-UAXXXXX");
        pageTracker._trackPageview();
    } else {
        setTimeout('checkGat()', 1000);
    }

}

checkGat()

What is the better solution? Why? and any additional comments?

A: 

This is all unnecessary. Just use the new Google Analytics Asynchronous Code; it does this for you.

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _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>

With this code, you store the tracking information in a JavaScript array (called _gaq) as early in the page as you want. Then, it only executes the call to Google Analytics once the the ga.js has loaded and ready. In other words, it does all of this for you, without needing to write complex loops, and you'll never have race conditions that result in JavaScript errors.

This has the added benefit of being non-blocking and thus slightly faster.

yc