javascriptanalyticssingle-page-applicationmatomofat-client

Using Piwik for a Single Page Application


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?


Solution

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