Leverage browser caching external files Leverage browser caching external files express express

Leverage browser caching external files


One solution is to reverse proxy the Google resources. Then you can add Cache-Control and other caching headers. If you're using Apache you can accomplish it as follows in your httpd.conf file:

ProxyRemote http://www.google-analytics.com http://yourinternalproxy:yourport<Location /analytics.js>  ProxyPass http://www.google-analytics.com/analytics.js  ProxyPassReverse http://www.google-analytics.com/analytics.js  Header set Cache-Control "max-age=86400"</Location>

The drawbacks of this are that:

  • You'll funnel a lot of additional traffic through your servers.
  • Obviously updates made by Google will take longer to appear for the user's of your site.


If you don't have access to httpd.conf file as rudolfv's answer there are several options here:

  1. the easiest one is you could copy its content each day to make sure your up to date
  2. we can employ the powers of cron, there is nice sample script using php posted here
  3. use a php script to generate the google analytics script on every request on the fly:

        $context = stream_context_create(['http' => ['Content-Type' => 'text/javascript', 'enable_cache' => true, 'enable_optimistic_cache' => true, 'read_cache_expiry_seconds' => 86400,]]);          echo file_get_contents("http://www.google-analytics.com/analytics.js", false, $context);
  4. use the power of .htaccess if your hosting provider allowing mod_headers & mod_proxy

        RewriteEngine On            Header set Cache-Control "max-age=86400"            RewriteRule ^js/analytics.js http://www.google-analytics.com/analytics.js [P]