Google Analytics for Backbone Apps

When you build a single-page web app with something like Backbone driving routes and managing browser history, the page load event is only going to happen once at the beginning of the session.

The standard Google Analytics javascript snippet doesn't work so well for these single-page apps. You should trigger an Analytics event when the user changes routes or otherwise causes a meaningful content change in your app.

This can be accomplished with a simple call to _gaq.push(['_trackPageview']) with an optional second argument for the URL path/fragment/route of your current page. To tell Google that a user just searched for Nicki Minaj on my music site, I'd just call _gaq.push(['_trackPageview'], '/search/Nicki-Minaj') for example.

You can get fancy if you are using Backbone, and override the Backbone.history.loadURL function to do this for you: https://github.com/kendagriff/backbone.analytics.

Leave a Reply