Host ga.js locally with a WordPress plugin

Recently, I’ve done some WordPress load optimization with Thomas Bensmann (read his post «Full score on Google PageSpeed, Pingdom and GTMetrix») and to achieve full effect, you do have to load the Google Analytics tracking script, ga.js, from your own server.

I like to use the plugin «Google Analytics for WordPress» by Joost de Valk (or «Yoast» as many know him by). It has a plethora of options, and nicely: one of them is to host your own ga.js locally (if you check «Show advanced settings:»):

Host ga.js locally

The problem

The issue with hosting your local version of ga.js is that Google frequently updates this script to enable new features and enhance old ones. This means that we have to create a cronjob to download the script every once in a while.

To enable maximum page load optimization we also have to ensure the path to the script is versioned – but not with the querystring:
We don’t want this: ga.js when using a far-future expiry date, the browsers doesn’t know when it’s updated
We don’t want this: ga.js?v=<versionnumber>
We want something like this: ga-<versionnumber>.js

We also want browsers who have an old (maybe cached) version of the HTML with a reference to an old version of the script to not only work, but preferably to download the newest version available.

Whenever there is an updated script available, we want the Google Analytics plugin to use it automatically.

 The solution

With a little use of the WordPress HTTP API, Options API and Cron functions  it was pretty quick to slap together a basic plugin that handles all our problems:

  1. Every 12 hours cron checks the modification time of our existing ga.js script and sends a request to Google
  2. If there’s a new script available, we download it and place it in a subfolder of the «WP Upload Dir»
  3. If an old version of the script existed, we delete the file and create a symlink to the new file
  4. We update the options for the Google Analytics plugin to use our new, local ga.js

That’s it. The script works fine (for me at least), but probably needs some polishing – and hooks so other people/plugins can utilize it.

It’s hosted on GitHub, so go ahead and play with it.

Update: The plugin is now also hosted in the WordPress.org plugin repository.

7 Comments

      1. Because of Real Time stats, you may lose some hits during script update and many other real time data would be unavailable. I have tried it any my personal opinion is not to follow it on production projects.

  1. For anyone reading this post. Yoast no longer supports the option to host the analytics.js file locally. Lucky for you, I recently published a plugin which takes care of everything for you. It downloads the analytics.js file to a folder on your own server, adds the tracking code to your theme’s header and keeps the javascript file updated using wp_cron. Click here to check it out.

Comments are closed.