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 minified1 version of the plugin and a well documented debug version.

Download [download id=”7″ format=”1″]

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:

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="" 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.

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.

  1. a compressed form of packaging JavaScript with all whitespace formatting and documentation being removed. []
  • Chris

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

    • Shamasis Bhattacharya

      $.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 script inclusion. If you still have confusion, mail me a scaled down version of your implementation code/sample.

      • Jeff Denver

        – 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 

      • Jeff Denver

        – 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 

  • JD

    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!

  • JD

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

    Thanks for the plugin!

    • Shamasis Bhattacharya

      Yes! This is exactly how it is to be done. :) You figured it out faster than I could reply you back.

  • Kim Burgess

    Nice one! Simple and effective. Makes for some much cleaner GA tracking.

  • PhilT

    — applicable to version 1.0 —
    Is it possible to use multiple tracking codes with this plugin?

    • Shamasis Bhattacharya

      — applicable to version 1.0 —
      As of version 1.0, it does not support multiple tracking codes.

  • Garry

    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.

    • Shamasis Bhattacharya

      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.

      • Kim Burgess

        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.

  • Bryan

    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″);
    <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>

    • Shamasis Bhattacharya

      No this is not the right way because your $.ga.setCookieTimeout executes before $.ga has actually loaded! :) You should put your codes in the $.ga.load() method’s call-back parameter function.

  • Bryan

    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″); }); });

    • Shamasis Bhattacharya

      This is the correct approach. :) Have you checked whether other things (barring campaign cookie timout) that if you set are working fine?

  • JMS

    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…

  • moltar

    @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.

  • JMS

    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 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.:

    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:" href="" rel="nofollow"></a>',
    cache: true,
    success: function() {
    if (typeof _gat != undefined) {
    pageTracker = _gat._getTracker(uid);
    } 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.

    • Shamasis Bhattacharya

      Uhmm… I will look into this issue and post an update ASAP.

      But was wondering… anyone else facing same issue?

  • gex

    or you can use the $(function(){ /* code here */ }); shortcut too.

  • AJ Mercer
    • Shamasis Bhattacharya

      All GA functions starting with underscore, is available for use. :)

  • Montana Flynn

    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.

  • gee

    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?

    • Shamasis Bhattacharya

      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 in your page and follow the instructions on this page.

  • t

    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?

    • Shamasis Bhattacharya

      I have fixed all issues. Will post updated JS as soon as I finish testing every aspect.

      • Steffen

        If possible, you should already implement the recently integrated

        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.
        BTW: _getTracker(account) is deprecated. The ga.js code is invoking _createTracker(opt_account, opt_name) now.

        • Shamasis Bhattacharya

          You will be surprised to know that any change made to ga.js gets AUTOMATICALLY integrated into this plugin. Test with _anonymizeIp(), it must already work! :)

          • Steffen

            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()
            –> undefined
            –> undefined
            –> 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

  • Oliver

    Does 2.0 support multiple tracking codes now?

    • Shamasis Bhattacharya

      Not yet. But 3.0 will.

  • simone

    i have a problem with the result of tracking:
    I use this code:
    var mySite = {
    DOMready: function()
    }, // end DOMReady
    analytics: function()
    $.ga.load("UA-XXXXXX-XX", function(pageTracker)
    } // 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???

  • Paul Prewitt

    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.

    • Shamasis Bhattacharya

      As a ready reckon, is one of the sites where it is deployed. You need to include this script in page head (see usage instructions above) and the rest this script will handle.

  • Paul Prewitt

    • Steffen

      I don’t hink you need to include this line in your code:

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

  • Brian

    Does this work with jQuery Mobile.  I tried to use it, but does not appear to be working with this framework.

    • Shamasis Bhattacharya

      I haven’t got the scope to test it with jQuery Mobile. I would definitely look into it and update you or this plugin! :)

  • Irena

    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?


  • Hungnm144

    I’ve a domain with multiple subdomains. how to use your plugin with my web? thank you!

  •ão-Márcio-Prado/100000460705707 João Márcio Prado

    Nice piece of code, thanks for share!

  • Joshua Canfield

    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.

  • Lou

    This looks very much for what I’m looking for but unfortunately the download link seems to be broken.

  • Stefan Pretty

    Can’t seem to download it and the jQuery plugin site is under re development. Any new links would be appreciated!

    • Shamasis Bhattacharya

      Download has been restored. :)

  • Anonymous

    where can i dowanload it?
    the link does not work and jquery page does not work too.

    • Shamasis Bhattacharya

      The link was down as jQuery plugin website was under re-development. As of now, I have updated the link with a new one.

  • Shamasis Bhattacharya

    Owing to the change that is taking place at jQuery Plugin website, the download is temporarily down. Things are being done to put it into place. Update will be posted here; follow the discussion.

  • Shamasis Bhattacharya

    The download has been restored!

  • Dave

    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?

  • Anonymous

    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.

  • AK

    Any progress on tracking multiple accounts? :)

  • Peter Fox

    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?

    • Shamasis Bhattacharya

      That’s odd. I guess I would then need to break out from the scope and raise the callback. Am on it.

  • Braian Mellor

    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…

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


    i try to do


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

    • Shamasis Bhattacharya

      load is an asynchronous function and as such you are calling trackPageView right after calling load and GA isn’t loaded yet. The 2nd param of load is called when GA scripts are actually ready.

      • Braian Mellor

        i understand that, but if i made samething like this

        it return this:
        RangeError: Maximum call stack size exceeded.

        any idea to track the clicks to new content?

        • Shamasis Bhattacharya

          Sorry, but am getting slightly confused with the sample code you’ve given. Could you elaborate what you’re trying to do?

  • Pingback: Marquage Php coté serveur pour google analytics()

  • Pingback: Resources for Extending Google Analytics - Resource Guru()

  • Pingback: Beauty Tip Jquery Plugin |