Leverage Browser Caching for External Resources

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.

Example: Nginx Proxy Setup

You can add the following directive to your Nginx configuration file:

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).

Stay up to Date