Monday, October 19, 2015

Google Analytics doesn't work a.k.a. name collision in JavaScript

Today is another great day I’ve encounter a trivial bug hard to catch. It goes as follow. I went to Google Analytics to setup a new page. I’ve followed the instruction and I’ve copied into a source:

<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-AAAAAAAA-X', 'auto');
  ga('send', 'pageview');

</script>

and it didn’t work ;-)

First I’ve thought is my mistake, i’ve put a code just before </html>, but after trying </head> it wasn’t any better.

I’ve tried to copy paste the code to developer console and tadah, it works! Here I should mention that I use both Google Closure Library and Google Closure Compiler on my site. After thinking and poking the code for a moment I’ve made an educated guess:

Closure compiler compiled code is colliding a name with Google Analytics!

Took me 1 minute to verify and yes, I’ve got it.

The solution was straight:

<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','dzialaj');

  dzialaj('create', 'UA-AAAAAAAA-X', 'auto');
  dzialaj('send', 'pageview');

</script>

Just for quick explanation, the string I’ve changed is a parameter to function which sets up a Google Analytics code on a website, it is a name that should be used as a Analytics main function and may be anything one wants.

No comments:

Post a Comment