7

Building a single page / fat client application and I'm wondering what the best practice is for including and tracking using http://piwik.org/

I'd like to use Piwik in a way that is architecturally sound and replacable with a different library in the future.

It seems that there are two basic options for tracking with Piwik:

  1. Fill up a global _paq array with commands, then load the script (it's unclear to me how to record future "page" views or change variables though)
  2. Get and use var myTracker = Piwik.getTracker()

_paq approach:

myApp.loadAnalytics = function() { /* dynamically insert piwik.php script */ }
myApp.track = function(pageName) {
  window._paq = window._paq || [];
  _paq.push(['setDocumentTitle', pageName]);
  _paq.push(["trackPageView"]);
}
myApp.loadAnalytics()

// Then, anywhere in the application, and as many times as I want (I hope :)
myApp.track('reports/eastWing') // Track a "page" change, lightbox event, or anything else

.getTracker() approach:

myApp.loadAnalytics = function() { /* dynamically insert piwik.php script */ }
myApp.track = function(pageName) {
  myApp.tracker = myApp.tracker || Piwik.getTracker('https://mysite.com', 1);
  myApp.tracker.trackPageView(pageName);
}
myApp.loadAnalytics()

// Then, anywhere in the application, and as many times as I want (I hope :)
myApp.track('reports/eastWing') // Track a "page" change, lightbox event, or anything else

Are these approaches functionally identical? Is one preferred over another for a single page app?

SimplGy
  • 20,079
  • 15
  • 107
  • 144

2 Answers2

1

The full solution using .getTracker looks like this: https://gist.github.com/SimplGy/5349360

Still not sure if it would be better to use the _paq array instead.

maxlath
  • 1,804
  • 15
  • 24
SimplGy
  • 20,079
  • 15
  • 107
  • 144
  • 1
    This abstraction using .getTracker works, is pretty neat in terms of isolating the application from the Analytics library, and was put into live code. I'm going to call this the answer for now, but I'd like to know if the creators have any guidelines for when to use _paq VS .getTracker() some day :) – SimplGy Apr 19 '13 at 22:39
1

To have the tracking library used (eg. piwik) completely independent from your application, you would need to write a small class that will proxy the functions to the Piwik tracker. Later if you change from Piwik to XYZ you can simply update this proxy class rather than updating multiple files that do some tracking.

The Async code is a must for your app (for example a call to any 'track*' method will send the request)

Matt
  • 161
  • 2
  • 3
  • What is "the async code"? To me both methods could be implemented asynchronously, so I'm confused. – SimplGy Apr 15 '13 at 02:54
  • I actually pored over this in some detail before asking my question. This documentation page mentions both of the methods under consideration. – SimplGy Apr 15 '13 at 17:28