PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

sjmartin picture sjmartin · Mar 20, 2015 · Viewed 156.7k times · Source

I'm on a quest to reach 100/100 on PageSpeed and i'm almost there. I'm trying to find a good solution to cache Google Analytics.

Here is the message I get:

Leverage browser caching Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network. Leverage browser caching for the following cacheable resources: http://www.google-analytics.com/analytics.js (2 hours)

The only solution i've found was from 2012 and I do not think it is a good solution. Essentially you copy the GA code and host it yourself. You then run a cron job to recheck Google once a day to grab the latest GA code and replace it.

http://diywpblog.com/leverage-browser-cache-optimize-google-analytics/

What else can I do to reach 100/100 while also using Google Analytics?

Thank you.

Answer

NiloVelez picture NiloVelez · Mar 21, 2016

Well, if Google is cheating on you, you can cheat Google back:

This is the user-agent for pageSpeed:

“Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.8 (KHTML, like Gecko; Google Page Speed Insights) Chrome/19.0.1084.36 Safari/536.8”

You can insert a conditional to avoid serving the analytics script to PageSpeed:

<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Speed Insights') === false): ?>
// your analytics code here
<?php endif; ?>

Obviously, it won't make any real improvement, but if your only concern is getting a 100/100 score this will do it.