ahmad Ahmad Nassri Blog

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:

  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

  ga('create', 'UA-XXXXX-XX', 'auto');
  ga('send', 'pageview');

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 = window.ga.q || [
      ['create', 'UA-XXXXX-XX', 'auto'],
      ['send', 'pageview']

    window.ga.l = new Date().getTime();

<script type="text/javascript" src="//www.google-analytics.com/analytics.js" async></script>