Chrome (and possibly other browsers) caching my script include



I am hosting a widget on a client's website that will be different for each page on the site.

To render the widget, the client includes a script tag on their pages. This script tag is loaded for every page on the site and the code that it returns depends on the page.

So, if this script gets cached, the end result is that we serve a widget for the wrong page.

Right now, when we serve the script, we set in the response headers

Cache-Control: max-age=0
Expires : 24 hours in the past

yet sometimes browsers still cache the script.


Is there a way to use http headers to stop caching in all cases or are we going to have to take a completely different approach?


The headers that topek recommended greatly improved the non-cacheability of the scripts. However, (again in Chrome who seems to be the most cache-aggressive) when using the back, forward, or reload buttons the script is still cached. If you actually CLICK on anything it will be fetched from the server.

It seems that the only foolproof way to stop caching will be to set script sources that are guaranteed to be different for each page load (as suggested by esilija and tejs).

Problem courtesy of: Hersheezy


Those two headers should do the trick:

response.setHeader("Cache-Control", "no-cache, must-revalidate");
response.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT");

or you set name according to the current page, e.g. when the user requests the page http://domain/posts/1 then the script name could be http://domain/script/scriptname/posts/1. With approach the script would still be cachable per page.

Do not append a query string on the script like script.js?random_string. Proxies don't play well with this approach. If you want to place a random string in the name, then put it before .js like this script-0934234234.js and rewrite the request on your server.

Solution courtesy of: topek


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.