Google Universal Analytics

support.google.com/analytics/answer/2790010

Official Implementation

HTML<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-123456-1', 'auto');
  ga('send', 'pageview');
</script>

Solution

This solution comes with minimum code change from official implementation. Google recommends adding the code after the opening <body> tag. Replace UA-123456-1 with your own Tracking ID.

HTML<script data-turbolinks-eval="false">
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-123456-1', 'auto');
</script>
<script>
  ga('set', 'location', location.href.split('#')[0]);
  ga('send', 'pageview', { "title": document.title });
</script>

Basically there are 3 changes:

  • Initialize ga in a JavaScript tag that is not re-evaluated
  • Set location manually, otherwise the URL of the page being tracked will not be send correctly (by default, location doesn't preserve the anchor)
  • Set title of the page manually so that is properly associated with your pageview

Related Issues: #166

Contributors

All solutions should be considered unofficial. There is no guarantee that a given solution will work with your application. If you find that a solution is insufficient, please let me know by submitting an issue on Github.