Track AJAX Link Clicks Using Google Analytics

4/22/2011: This blog post was completely rewritten to describe page tracking with Analytics' asynchronous loading method.

With more and more websites becoming completely AJAX-driven, the typical "do this every time a page loads" strategy isn't always enough. This is especially try if you're using Google Analytics or other analytics tracking software. Google is, of course, forward-thinking so they've provided a way to easily track page views of AJAX requests.

The Google Analytics JavaScript

The current standard for loading Google Analytics is the asynchronous method:

var _gaq=[["_setAccount","UA-#######-#"],["_trackPageview"]];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js";
s.parentNode.insertBefore(g,s)}(document,"script"));

That bit tracks the initial page load but not subsequent AJAX calls. Any time you want to track a page load, place add the following snippet:

// "_trackEvent" is the pageview event, 
_gaq.push(['_trackPageview', '/some-page']);

_trackPageview is used again but this time we provide the URL of the AJAX address that was loaded. Using the small JavaScript snippet above allows you to keep track of pageviews just as you would if the entire page reloaded. I'd recommend using this snippet with MooTools' History plugin.

The Old Method

If you're still using the synchronous method of loading Google Analytics, the following snippet will accomplish the same task:

pageTracker._trackPageview('/some-page');

It's great to know that Google Analytics is as dynamic as your web applications. Allowing developers to track AJAX page clicks prevents the need to code apps just to keep track of statistics.


Comments

  1. Christof Haemmerle

    you want to change want to check on the parent object(here window) if it has a function called pageTracker otherwise it will break your app.

    if(window.pageTracker)

  2. Chris Bowyer

    Interesting, but, the current (and it has been for some time) Google Analytics JavaScript (that should be placed immediately before the closing head tag) is as follows…

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

    • David Walsh

      What is this in reference to?

    • aykak

      In my view I think he only give refrence for puttinh google analytics codes in Head section,,, But don’t know what he exactly mean.

  3. aykak

    nice tuts keep up sometimes i am viewing your tuts and it’s usefull.

  4. Stephanie

    Hi David,

    To clarify – does this

    _gaq.push(['_trackPageview', '/some-page']);

    go on the page being loaded, or is it added to the main page which is doing the loading? If it goes on the page being loaded, does it replace the original trackPageview or get added to the original tracking code?

    Thanks!

    • Ryan Mac

      You would call the original GA Code your head when the page first loads. Then on completion of subsequent ajax calls use:
      _gaq.push(['_trackPageview', '/some-page']);
      Use jquery as an example:

      $.ajax({
      url: "test.html",
      context: document.body,
      success: function(){
      _gaq.push(['_trackPageview', '/text.html']);
      }
      });

  5. fernando

    Hey, im not sure I get it. I have a 100% Ajax webapp and in google analytics I only get information for woojah.com/ But that page hardlly has anything. Everything is generated dynamically so my question is, do I have to put _gaq.push(['_trackPageview', 'woojah.com/#mysubpage']) for every subpage I have in my woojah.html?

  6. Peter Drinnan

    Hi Fernando,

    _trackPageView generates a virtual page but is otherwise similar to _trackEvent.

    Since it is just Javascript it can be called whenever an Ajax “page” loads. If, for example, you are using a WordPress site and want to track the loading of content on some plugins that use Ajax, you can modify the plugins Ajax calls to also call the _gaq.push() function. The “pages” that are recorded on Google Analytics are really just labels for the Ajax event (or any other event you like), so you should make the parameters obvious to anyone reading a GA report.

    Here is an example straight from Google Code in which a user plays a specific video using _trackEvent:

    _gaq.push(['_trackEvent', 'Videos', 'Play', 'Gone With the Wind']);

    See the similarity?

  7. Peter Drinnan

    _trackPageView generates a virtual page but is otherwise similar to _trackEvent. Since it is just Javascript it can be called whenever an Ajax “page” loads. If, for example, you are using a WordPress site and want to track the loading of content on some plugins that use Ajax, you can modify the plugins Ajax calls to also call the _gaq.push() function. The “pages” that are recorded on Google Analytics are really just labels for the Ajax event (or any other event you like), so you should make the parameters obvious to anyone reading a GA report. Here is an example straight from Google Code in which a user plays a specific video using _trackEvent: _gaq.push(['_trackEvent', 'Videos', 'Play', 'Gone With the Wind']);

    See the similarity?


Be Heard!

Share your thoughts without being a jerk! And wrap your code in <code> tags, f00!

Name*:
Email*:
Website: