You’re trying to achieve 100/100 on your PageSpeed Insights speed score, but you also load external resources such as Google Analytics. How do you get past the “Leverage browser caching” fix?
The Problem
You can control the cache expiration date for resources that are within your domain, but you have no control over resources loaded from a different domain. For external resources such as Google Analytics, where you need to include a script like http://www.google-analytics.com/ga.js, PageSpeed Insights will complain that “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”.
The Solution: Setup a Proxy
There’s multiple ways to do this, but the idea is simple:
- Periodically copy the resource to your domain (to keep it up to date).
- Serve the resource from your domain, where you can control the cache expiration date.
You would then replace the URL of //www.google-analytics.com/ga.js in your Analytics script to point to your domain.
1 2 3 4 5 6 7 |
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.yourwebsite.com/ga.js','ga'); ga('create', 'UA-XXXXXXXX-1', 'yourwebsite.com'); ga('send', 'pageview'); |
Example: Nginx Proxy Setup
You can add the following directive to your Nginx configuration file:
1 2 3 4 5 6 |
rewrite ^/ga.js$ /ga/ last; location /ga/ { proxy_pass http://www.google-analytics.com/ga.js; expires 7d; break; } |
This will redirect all requests for ga.js (from your domain) to Google’s URL. Note that we chose a relatively short expiration date (7 days).
Final Notes
- Any changes to ga.js will not be propagated to clients who have visited your website for 7 days. This might result in your Analytics to malfunction for up to a week if and when Google changes the script. Lower the expiration date if this is not acceptable (or avoid this technique altogether).
- Depending on your website’s load, this approach might result in performance penalties.
- PageSpeed Insights is just a tool; just because it says something should be fixed, it doesn’t necessarily mean that performance will improve (in fact, it might do just the opposite).