Paulund

Fixing Analytics Leverage Browser Caching

If you've read my previous articles you would of seen a post from last month about trying to reach the 100/100 on Google's pagespeed tool. This doesn't necessarily improve your site but it shows it's built in a way to perform well on both mobile and desktop computers. Also Google loves fast websites so if you can make your website perform well it will do better in the search results. I have now achieved this 100/100 score but last month I was having a problem at reaching the 100 goal. The problem was actually with another of Google's own products, Google analytics.

As the Google analytics file is being served from Google they control the HTTP headers to set caching on the file and they've have also stated that they're aware of the problem but aren't going to fix it because it will mean changes they make take too long to propagate.

How To Fix The Problem

To fix this we need to serve Google analytics from a different location where the HTTP headers can be controlled to leverage browser caching. This lead me to find a blog post by Jesse Luoto and how he fixed this issue. Fixing the last point on Google PageSpeed Insights

He's created a repository on Github that you can use for this problem called GA-Lite. It's a small subset of Google Analytics that uses the Google Analytics Measurement Protocol REST API. You can either use this library on your own server and fix the problem that way or use the CDN setup to server the ga-lite.js files.


<script src="https://cdn.jsdelivr.net/ga-lite/latest/ga-lite.min.js" async></script>
<script>
var galite = galite || {};
galite.UA = 'UA-XXXXXX'; // Insert your tracking code here
</script>

Notice the word lite in the URL, this is because the script doesn't have all the feature of normal analytics it only really does the essentials like page views. ## Alternative Solution

Another approach to take is to simply copy the analytics.js file and host it locally. The problem with this approach is that if Google updates the Javascript code then these changes will not be followed on your website. The solution to this would be to cache a local copy of Google analytics.js file everyday and store locally and serve this to your visitors instead of Googles own. As you're caching a local version each day when Google makes changes you will pick these up on the next caching loop. If you're using WordPress you can do this using the built in scheduled tasks using wp_cron.