SimplGy
SimplGy

Reputation: 20437

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?

Upvotes: 7

Views: 4907

Answers (2)

SimplGy
SimplGy

Reputation: 20437

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.

Upvotes: 1

Matt
Matt

Reputation: 171

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)

Upvotes: 1

Related Questions