Skip to content

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.

Ahmad Nassri
Ahmad Nassri
1 min read
Optimizing Google Analytics Tracking Code (Revisited)

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>
Blog

Ahmad Nassri Twitter

Fractional CTO, Co-Founder of Cor, Developer Accelerator, Startup Advisor, Entrepreneur, Founder of REFACTOR Community. Previously: npm, TELUS, Kong, CBC/Radio-Canada, BlackBerry


Related Posts

The Modern Application Model

Most of today’s software development is occurring within the Application Layer as defined by the OSI Model. However that definition is a bit dated and does not exactly reflect today’s technology. We need a new model to visualize what we, Application Software Developers, are building.

The Modern Application Model

The New Normal — Scaling the challenges of a Modern CTO

Whether you’re a Founding CTO or an Enterprise CTO, you cannot go at it alone. You have to hire a team around you to help delegate and distribute a modern CTO’s responsibilities and overlapping technical domains, such as CIO, CDO, CMO, etc.

The New Normal — Scaling the challenges of a Modern CTO

Challenges of a Modern CTO

A CTO needs to be able to operate and be experienced in many areas beyond just the tactical. To be successful, they require Technical & People Leadership experience.

Challenges of a Modern CTO