Google Analytics jQuery Plugin

30 comments   5,014 views

“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[1] version of the plugin and also a well documented debug version.

Download
jQuery Google Analytics Plugin (version 2.0.0, 1.83 kB, 832 dowloads)

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.

  1. <script src="jquery.ga/jquery.ga.js" type="text/javascript"></script>
  2. <script type="text/javascript">
  3. $(document).ready( function() { $.ga.load("UA-xxxxxx-x"); } );
  4. </script>

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.

  1. <script type="text/javascript">
  2. $(document).ready( function() {
  3.    $.ga.load("UA-xxxxxx-x", <strong>function(pageTracker) {
  4.       // an example of a line of what your code can be…
  5.       pageTracker._setDomainName(".example.com");
  6.    }</strong>);
  7. });
  8. </script>

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.

  1. jQuery.ajax({
  2.    type: "GET",
  3.    url: (document.location.protocol == "https:" ?
  4.       "https://ssl" : "http://www") + ".google-analytics.com/ga.js",
  5.    cache: true,
  6.    success: function() {
  7.       if (typeof _gat != undefined) {
  8.          pageTracker = _gat._getTracker(uid);
  9.          pageTracker._trackPageview();
  10.       } else {
  11.          throw "_gat has not been defined";
  12.       }
  13.    },
  14.    dataType: "script",
  15.    data: null
  16. });

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.

Footnotes:

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

{ 30 comments… read them below or add one }

1 Chris September 5, 2009 at 21:26

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.

Reply

2 Shamasis Bhattacharya September 5, 2009 at 22:06

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

Reply

3 JD September 16, 2009 at 16:14

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

Reply

4 JD September 16, 2009 at 17:17

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

Thanks for the plugin!
Jonathan

Reply

5 Shamasis Bhattacharya September 16, 2009 at 17:59

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

Reply

6 Kim Burgess September 30, 2009 at 01:13

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

Reply

7 PhilT October 21, 2009 at 15:23

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

Reply

8 Shamasis Bhattacharya October 22, 2009 at 01:00

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

Reply

9 Garry October 21, 2009 at 21:05

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.
 

Reply

10 Shamasis Bhattacharya October 22, 2009 at 01:03

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.

Reply

11 Kim Burgess October 22, 2009 at 04:30

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.

Reply

12 Bryan October 26, 2009 at 08:51

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>

Reply

13 Shamasis Bhattacharya November 7, 2009 at 11:44

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.

Reply

14 Bryan October 27, 2009 at 07:23

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

Reply

15 Shamasis Bhattacharya November 7, 2009 at 11:45

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

Reply

16 JMS November 9, 2009 at 22:31

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…

Reply

17 moltar December 3, 2009 at 18:50

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

Reply

18 JMS December 4, 2009 at 02:57

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&lt;/a>' : '<a title="Linkification: http://www" href="http://www/" rel="nofollow">http://www&lt;/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.

Reply

19 Shamasis Bhattacharya December 10, 2009 at 20:01

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

But was wondering… anyone else facing same issue?

Reply

20 gex December 10, 2009 at 00:51

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

Reply

21 AJ Mercer February 3, 2010 at 09:42
22 Shamasis Bhattacharya February 10, 2010 at 00:31

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

Reply

23 Montana Flynn March 14, 2010 at 08:54

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.

Reply

24 gee March 24, 2010 at 15:12

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?

Reply

25 Shamasis Bhattacharya March 25, 2010 at 09:34

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.

Reply

26 t April 30, 2010 at 20:56

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?

Reply

27 Shamasis Bhattacharya May 9, 2010 at 14:53

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

Reply

28 Steffen May 26, 2010 at 21:38

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.

Reply

29 Shamasis Bhattacharya May 27, 2010 at 11:16

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! :)

Reply

30 Steffen May 29, 2010 at 23:33

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

Leave a Comment