patkua@work

Making google analytics work with requirejs

We were trying to template google analytics and make it part of our requirejs setup. When we did what we thought was obvious to wrap it in a module and declare a dependency on it, it seemed to fail quite miserably.

The trick was that we missed that you needed to export a global variable. This means in the javascript file initialising google analytics we had to add the following code block

var registerGoogleAnalytics = function(accountId) {
  var _gaq = _gaq || [];
  if (window) {
    window._gaq = _gaq; // export as global
  }
  _gaq.push(['_setAccount', accountId]);
  _gaq.push(['_trackPageview']);

  // rest of google analytics initialiser script...
}

Some links that helped us working this out:

Exit mobile version