Wednesday, October 5, 2011

Google Analytics code in external .js file

Google Analytics JavaScript code does not have to be inline. New, asynchronous GA tracker can be as well invoked from external JavaScript file with no - at least noticeable - impact on performance.

I have read on one of the forums that with putting GA code in an external file you lose the benefit of asynchronous architecture which is quite obviously bollocks. One of the main benefits mentioned on Google Analytics help page is that you can start tracking user events even before the tracking code loads and you still have that! The GA JavaScript still loads in the background and the page load time is as with inline Google Analytics code.
The best thing is that there is nothing special you have to do. Just get the JavaScript code generated in your Google Analytics account and instead of pasting it directly onto the page paste it into .js file and refer to that file from your page. More or less as follows.
On your page
<script src="file_containing_google_analytics.js" type="text/javascript"></script>
Inside the file_containig_google_analytics.js:
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
  _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);
})();
Have fun!

No comments:

Post a Comment