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:»):
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:
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.
- Every 12 hours cron checks the modification time of our existing ga.js script and sends a request to Google
- If there’s a new script available, we download it and place it in a subfolder of the «WP Upload Dir»
- If an old version of the script existed, we delete the file and create a symlink to the new file
- 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.