How to track page views in a SinglePage App

The google analytics snippet tracks regular page views every time the page gets reloaded. That happens if you navigate to another page or your reload the current page.

But if you have a AJAX heavy SinglePage Application, for example build with Backbone.JS or ember.js, than the default code snippet from Google is not enough. Another use case is if you want to track a JavaScript/CSS popups in Google Analytics.

Well. All you need is the default GA snippet. Which looks like this.

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXX-Y']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

The good thing is that you can trigger page views with the JavaScript Google provides you. All you need to do is to trigger this code.

  _gaq.push(['_trackPageview', '/popup']);

The last parameter is a fictional path. This is what you will see in the analytics. You could call this code in the “onclick” event of a button or link. I wrote this convenience method.

function page_view(path){
 if (_gaq){
   _gaq.push(['_trackPageview', path]);
 } else {
   ga('send', 'pageview', path);

With that I am now able to track JavaScript popups, click on js/css Tabs and clicks in SinglePage Applications. All visible in Google Analytics.

Published by Robert Reiz

CEO @ VersionEye. Passionated software developer since 1998.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: