Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put Google analytics in external JS?

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-123-2']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

Apart from caching issues (if I change my tracking ID), is there anything else I need to be aware of? Will it still function? It recommends putting it before </head>, all my other JS is before </body>, is it ok to put it there?

like image 308
Tom Gullen Avatar asked Mar 05 '11 16:03

Tom Gullen


1 Answers

Besides potentially needing to change the tracking code, the only potential issue I can think of is that, in the scheme of things, visitors who leave between when that file is requested and when it arrives will not be tracked. Or, if for some bizarre reason, the external script fails to load, you will not have tracked that user. Besides that, you're safe to include it in an external script.

like image 137
Yahel Avatar answered Sep 29 '22 20:09

Yahel