Tagged: requirejs

Find and track frontend bugs using Google Analytics

Find your Frontend bugs and stop guessing ROI for a bug fix.

This post describes how to use Google Analytics with requirejs to track errors in frontend.

Google Analytics events

GA events are grouped by Category, Action and Label. All JavaScript errors can be captured using window.onerror -handler.
As end result GA looks like this in case of a frontend bug:

event-stats

Setting things up with Google Analytics

  • Create a GA account and two properties: one for testing purposes (handy also for integration tests) and one for production.
  • Configure your local web server to serve pages you are developing singe GA will not accept file protocol.
  • GA is always disabled for localhost. In order to test locally use IP address 127.0.0.1 or some custom domain name. With Mac you can just use computer_name.local.

Basic setup

window._gaq = window._gaq || []
window._gaq.push(['_setAccount', (isProduction ? productionAccountId : testAccountId)])
window._gaq.push(['_trackPageview'])
require(['http://www.google-analytics.com/ga.js'])

Tracking JavaScript errors

window.onerror(function(e) {
  var category = 'JavaScript error'
  var action = e.message
  var label = e.filename + ':' + e.lineno
  _gaq.push(['_trackEvent', category, action, label]);
}

Tracking ajax errors

function ajaxErrorHandler(e) {
  var category = 'Ajax error'
  var action = e.status + ' - ' + e.statusText
  var label = e.responseText
  _gaq.push(['_trackEvent', category, action, label]);
}

$.get('nonExistingUrl.com', $.noop).fail(ajaxErrorHandler)

Debugging

In order to make debugging easier Google provides http://www.google-analytics.com/u/ga_debug.js instead of http://www.google-analytics.com/ga.js to log to console all tracking events.

Here’s the code for requiring proper GA bootstrap file:

function getGaUrl(isDebug) {
  var isHttps = 'https:' === document.location.protocol
  return (isHttps ? 'https://ssl' : 'http://www') + '.google-analytics.com/' + 
    (isDebug ? 'u/ga_debug.js' : 'ga.js')
}
require([getGaUrl(true)])

With this configuration GA will show following information in console for different tracking events.

ga-debug

Try out a Live Demo.

Full example can be found in Github

Advertisements