Google Analytics jQuery Plugin

“Google Analytics jQuery Plugin” is a jQuery Plugin!

When used in conjunction with the famous jQuery framework, this plugin allows easy integration of Google Analytics on any webpage.

Google Analytics is an enterprise-class web analytics solution that gives you rich insights into your website traffic and marketing effectiveness.

Advantages of using this plugin

  • Extremely simple to use. Copy-paste (almost) anywhere within your page. It just works!
  • Familiar usage syntax for jQuery fanatics!
  • No need to write messy JavaScript codes within HTML body. Makes it easier to maintain pages, besides making the HTML codes sexier.
  • Does not use the infamous document.write method to insert JavaScript.
  • Increases the performance of your web-pages by loading Google Analytics codes after the current page is fully loaded.
  • Does not stop page loading while Google Analytics ga.js file is loading. In effect, prevents the annoying delay of loading pages due to slow response from Google Analytics servers.
  • Extremely lightweight. The minified version of this plugin is as small as 688 bytes!
  • New: Dynamically binds to the Google Analytics pageTracker and allows easier access to Google Analytics API

Download Google Analytics jQuery Plugin

You can download this plugin for free by following the link provided below. The downloaded compressed (zipped) package contains a minified ((a compressed form of packaging JavaScript with all whitespace formatting and documentation being removed.)) version of the plugin and a well documented debug version.

Download [Download not found]

This plugin complies and conforms to the licensing scheme of jQuery. You are free to redistribute the code and use it in any of your applications.

Also available on jQuery plugin repository:
http://plugins.jquery.com/project/ga

Usage Instructions

Using this plugin is as simple as including this plugin JavaScript file along with other JavaScript files of your pages HTML section and then replacing xxxxxx-x in that code with your Analytics account number.

Installing this plugin and the Google Analytics codes:

After, extracting the downloaded package to the desired folder on your server, you would need to include the code snippet given below, within the section of all your pages where you want this plugin to work.

You might also need to change the path to the plugin file by providing the correct path in src="jquery.ga/jquery.ga.js" attribute.

Using Google Analytics Tracking API with this plugin:

This plugin dynamically maps all Google Analytics tracking methods to $.ga for easy access. What this means is that, whatever public API Google Analytics pageTracker uses, the same is applicable to this plugin.

For example, to invoke the pageTracker._trackEvent(category, action, opt_label, opt_value) method, you simply need to call $.ga.trackEvent(category, action, opt_label, opt_value)

Current list of methods that this plugin automatically binds on to: (This is not the ultimate list. The plugin binds on to all functions that begin with an underscore “_”.)

To get the complete Google Analytics Tracking API, visit Google Analytics Tracking API Reference page.

Executing a callback function:

You can execute a callback function upon load of Google Analytics Code. This can be done by passing a function to the 2nd parameter of the load(uid, callback) method.

The first parameter sent to the callback method is the pageTracker object of Google Analytics.

How this plugin works?

This plugin uses the robust and reliable jQuery.ajax API to fetch the Google Analytics core JavaScript file (ga.js) after the document load is completed. It does not use the jQuery.getScript API as it prevents the loaded script from being cached.

The core code that does this is illustrated below.

jQuery.ajax({
   type: "GET",
   url: (document.location.protocol == "https:" ?
      "https://ssl" : "http://www") + ".google-analytics.com/ga.js",
   cache: true,
   success: function() {
      if (typeof _gat != undefined) {
         pageTracker = _gat._getTracker(uid);
         pageTracker._trackPageview();
      } else {
         throw "_gat has not been defined";
      }
   },
   dataType: "script",
   data: null
});

After loading Google Analytics, it dynamically maps all tracker API to itself. This also implies that should, Google Analytics change its API, this plugin should automatically adapt to the changes.

65 Replies to “Google Analytics jQuery Plugin”

  1. Is there some trickery necessary to reference jquery.ga.js externally and also make calls through $.ga from another, externally referenced script file (that is included after jquery.ga.js)?
    It always tells me $.ga is undefined.

    1. $.ga is defined only after complete page load. So, all your settings, referencing, etc with $.ga should be defined within jQuery(document).ready(function() { }); within page body after jquery.ga.js script inclusion. If you still have confusion, mail me a scaled down version of your implementation code/sample.

      1. – liked it, got feedback from a jquery guy too it’s gr8.. comings days wud luv to see something from u in future similar as  analyticsengine.net.. 

      2. – liked it, got feedback from a jquery guy too it’s gr8.. comings days wud luv to see something from u in future similar as  analyticsengine.net.. 

  2. Hi,
    I’m trying to integrate your plugin with the scrollSerial plugin from Ariel Flesher, but I’m a complete jQuery noob.  How would you suggest that I call the $.ga.trackPageview from that plugin, is there an event that I can hook into?  Sorry, out of my depth here!
    Cheers,
    Jonathan

  3. Hi, fixed it myself, this line works:
    $('#slider .navigation').find('a').click(function() {$.ga.trackPageview(this.href)} );

    Thanks for the plugin!
    Jonathan

  4. Would loading the tracking script after the dom has loaded reduce the accuracy of the tracking? In the additional time it takes for the DOM to load plus then the ga script, more users could have clicked on to another page and so won’t be tracked.
    I have found that any delay in loading the ga script causes more self referrers, as in more refferals coming from your own site as the script hasn’t loaded at the point of them clicking an internal link and then ga loading on the next page thinking the user has been refferred from the same site.
    This becomes more of an issue on larger sites as the tracking could be missing a higher number of users.
    Just wondered if anyone else had come across this.
     

    1. Yes you are right. But this is a fractional issue compared to the bad quality of service one provides to website users due to delay or error in loading ga.js
      What I may be interested in future version of this plugin is loading ga.js normally for the first time and for every subsequent load, do it after DOM load and from cache.

      1. Nice idea. Definately agree with your stance on user experience trumping metrics collection. There’s no point gathering usage info if in doing so you are decreasing the quality of experience provided. After all, in most casing the reason for gathering metrics is so that you can improve an experience.

  5. Hi, Great plugin.
    I have gotten load ga and track events to work.  I am trying to change the Cookie Timeout.  Is the setup below correct?
    I used to use pageTracker._setCookieTimeout(“604800″);
    Thanks,
    Bryan
    <script type=”text/javascript”> $(document).ready( function() { $.ga.load(‘UA-XXXXXX-X’); } ); </script> <script type=”text/javascript”> $(‘A[rel=”external”]’).click(function() { $.ga.track(‘Links’, ‘Click’); }); </script> <script type=”text/javascript”> $.ga.setCookieTimeout(604800); </script>

  6. Should I approach it more like this?  The ga file loads, but the campaign cookie (utmz) stays at 6 months.

    $(document).ready( function() { $.ga.load(‘UA-XXXXXX-XX’, function(pageTracker) { pageTracker._setCookieTimeout(“604800”); }); });

  7. I’m trying to use the ecommerce tracking (addTrans/addItem/TrackTrans) but am having an issue with timing.  If I delay TrackTrans for a second via setTimeout or attach it to a page unload event, things work perfectly.  If I just fire off every event in sequence, the transaction never gets finalized on Google’s end.

    Any suggestions on how I can avoid this?  Is there any chance I can just tack callback functions after each of the addTrans/addItem calls and use those to essentially string the calls together in a somewhat synchronous manner?
     
    Thanks in advance…

  8. @JMS: you need to make sure you wrap all calls in:
    $(document).ready( function() { /* … your code … */ });
    That code basically ensures that all the necessary JS code has loaded and is “ready” to be used. What is probably happening is that you are running your code, before the parent, tracking, code has fully loaded.

  9. My code already was wrapped in $(document).ready( function() { /* … your code … */ });, so that definitely wasn’t it.
    Sadly, I never could get this to work, so I ended up abandoning the plugin in favor of just rolling my own code based on the parts of jquery.ga that I liked.  In order to ensure that all GA-related calls happened post-_gat instantiation, I just stuck everything inside another function that gets called at the end of the success function, i.e.:

    jQuery.ajax({
    type: 'GET',
    url: (document.location.protocol == 'https:' ?
    '<a title="Linkification: https://ssl" href="https://ssl/" rel="nofollow">https://ssl</a>' : '<a title="Linkification: http://www" href="http://www/" rel="nofollow">http://www</a>') + '.<a title="Linkification: http://google-analytics.com/ga.js" href="http://google-analytics.com/ga.js" rel="nofollow">google-analytics.com/ga.js</a>',
    cache: true,
    success: function() {
    if (typeof _gat != undefined) {
    pageTracker = _gat._getTracker(uid);
    pageTracker._trackPageview();
    OtherOnloadTrackingEvents();
    } else {
    throw '_gat has not been defined';
    }
    },
    dataType: 'script',
    data: null
    });

    The function checks for additional tracking-related functions and, if present, calls them.  Not ideal, but things have been rock solid, so I’m not complaining.

  10. I am in the process of making a jQuery plugin for the new async analytics code.    I have been using it and very impressed with its results in event tracking.   The standard code often fails to register an action before the page reloads.   A nice fix is to tack on a 1s timeout to the link.

  11. how is this plugin supposed to work? what is the output? is there a sample page somewhere? I dont see anything displayed after using the code mentioned above.  can i view the analytics data with this plugin?

    1. If you have Google Analytics included in your web-page, this is an alternative method to do the same. Everything else remains unchanged.

      However, it adds some features to existing GA like: lesser page-load time, neater API, jQuery syntax, etc.

      You need to include jquery.js and jquery.ga.js in your page and follow the instructions on this page.

  12. I have a similar problem to the one that JMS was having with the e-commerce tracking. All events are wrapped in $(function() { }); but because the script takes its time to load it the bind() function in your script hasn’t been fired and it throws an error and tells me the $.ga.XXX functions I am trying to call are undefined.
    Have you got any solutions?

      1. If possible, you should already implement the recently integrated
         

        _gat._anonymizeIp();

         
        into the $.ga.load(uid, callback) function because the load() function already performs the Tracking [line 81: t._trackPageview()] and _anonymizeIp() should be invoked before _trackPageview() as far as I understand the updated API.
        http://code.google.com/apis/analytics/docs/gaJS/gaJSApi_gat.html#_gat._anonymizeIp
        BTW: _getTracker(account) is deprecated. The ga.js code is invoking _createTracker(opt_account, opt_name) now.

          1. Hi Shamasis,
            the reason I think it won’t work is because of
             
            1.) _anonymizeIp() is a method of _gat, not of the pageTracker which would get automatically mapped to $.ga through  bind()
             
            $.ga._anonymizeIp()
            –> undefined
             
            $.ga.anonymizeIp()
            –> undefined
             
            _gat._anonymizeIp()
            –> function (){i.Va=r}
             
             
            2.) You can’t use the callback argument of ga.load() because as already mentioned _anonymizeIp() is not a method of pageTracker
             
            $.ga.load(‘UA-XXXXXX-XX’, function(pageTracker) { pageTracker._anonymizeIp(); });
            -> undefined
            -> Uncaught TypeError: Object [object Object] has no method ‘_anonymizeIp’
             
            Any idea?
            — Steffen

  13. hi,
    i have a problem with the result of tracking:
    I use this code:
    var mySite = {
    DOMready: function()
    {
    mySite.analytics();
    }, // end DOMReady
    analytics: function()
    {
    $.ga.load("UA-XXXXXX-XX", function(pageTracker)
    {
    $.ga.trackPageview()
    pageTracker._trackPageview();
    }
    )   
    }
    } // end var mySite
    $(document).ready(function() { mySite.DOMready() });

    When i visit a page 1 time in the results of analytics the page is visited 3 times
    I don’t understand…any help???
    Thanks
    Simone

  14. Do you have a working example/demo site using this script? I’d really like to see how you’d recommend to implement it.
    From my limited understanding the script section could be loaded in the <head> section but according to GA it should be loaded after the <body>. Where do you recommend putting it?
    Sorry I’m not the best with JavaScript.

  15. Any idea why this code would be generating 2 calls to the __utm.gif tracker. I'm thinking that it is doubling the stats as they are both unique calls.
    
    <script src="jquery.ga.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
    $(document).ready( function() { 
    $.ga.load("UA-500915-1", function(pageTracker) { 
    // an example of a line of what your code can be… 
    pageTracker._setDomainName(".hogtags.org"); 
    pageTracker._setAllowLinker(true); 
    pageTracker._setAllowHash(false); 
    pageTracker._trackPageview(); 
    });
    // All hyperlinks starting with http but does not contain the domain of the current document. 
    $("a[href^=http]:not([href*='hogtags.org'])").click(function(){ 
    $.ga.trackEvent( 'outbound', 'click', this.href); 
    });
    }); 
    </script>
    
    1. I don’t hink you need to include this line in your code:
       

      pageTracker._trackPageview(); 

       
      The $.ga.load() function already includes a trackPageview() call in the ajax success function when the ga.js file was downloaded.

                      // create a new tracker
                      t = _gat._getTracker(uid);
  16. Hi Shamasis,

    about tracking eventes,
    I wanted to know if i should use an onclick event when i call $.ga.trackEvent(category, action, opt_label, opt_value) on the ‘a href’ tag?

    Do you have an example for tracking events script?

    Thanks,
    Irena

  17. Shamasis, just wanted to thank you for your hard work on this plugin. This is a great plugin that if utilized really helps me with quick tracking methods on over 30 different websites and site designs. Great job. If you had a simple (and elegant– not tacky) donate button, I would gladly through you a few dollars.
    Thanks again.

  18. This may be just the thing I am looking for, however my .net Ecommerce has a single page for checkout that once the form is validated, send the order data to my backend for processing and returns an order number when successful.  how to I set this up to do Ecommerce tracking only if I get the order number back?

  19. Hey I implemented this in my code and have not been able to get this working for the trackPageView method it create an exception in the ga.js file. I was just wondering if anyone else had had this issue too.

  20. I’ve got a slight problem with this, the callback seems to fire before all the setup of the library e.g. The cookies created occur after the callback, any opinions on this?

  21. Hello! nice work! it actually works fine. But i have this problem, i’m trying to track that’s happend in the page.

    $(document).ready(function() {
    $.ga.load(“UA-32XXXX44-1”, function(pageTracker) {
    // an example of a line of what your code can be…
    pageTracker._setDomainName(“XXXXX.com”);
    pageTracker._trackPageview(“/”);
    });
    });

    It load fine, but when i change part of the code by

    $(‘#XXXX’).load(source);

    i try to do

    $.ga.trackPageview(source);

    but it breaks all. Any help???
    thank you!!!

      1. i understand that, but if i made samething like this

        $(‘#XXXX’).load(source,function(){
        $(‘#XXXX’).slideDown(800);
        $.ga.trackPageview(source);
        });
        it return this:
        RangeError: Maximum call stack size exceeded.

        any idea to track the clicks to new content?

Leave a Reply