Optimizing Google Analytics Tracking Code (Revisited)
Google’s snippet for Analytics is optimized for maximum compatibility, not for performance, and certainly not for clarity. Here’s how to make it faster.
A few years ago, I analyzed the Google Analytics tracking code and provided a simpler, and cleaner version.
Since then, Google released a new version of the tracking code as part of the Universal Analytics Upgrade:
<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-XXXXX-XX', 'auto');
ga('send', 'pageview');
</script>
Again, Google is attempting to maximize compatibility so the tracking code would work on any page, regardless of the HTML structure.
Following the same analysis we can derive a simpler version that gives us more control and readability:
<script type="text/javascript">
function setupGoogleAnalytics () {
window.GoogleAnalyticsObject = 'ga';
window.ga = window.ga || function () {
window.ga.q.push(arguments);
};
window.ga.q = window.ga.q || [
['create', 'UA-XXXXX-XX', 'auto'],
['send', 'pageview']
];
window.ga.l = new Date().getTime();
}
</script>
<script type="text/javascript" src="//www.google-analytics.com/analytics.js" async></script>