tincho87
tincho87

Reputation: 379

Avoid Javascript/Css caching

I've been searching a lot about this, but I can't find any solution that really works: we're building a web app using lot of javascript/css files, which are modified at anytime. The thing is that we need that the client's browser always gets the last version of the script.

We tried adding the GET query (?v=CurrentDate), but the browser keeps loading the old script until you hit refresh a few times or do CTRL+F5.

One thing we want to avoid is to store those files in different folders like /scripts/v1.0/, then /scripts/v2.0/...

We're using ASP.NET MVC 5, Bootstrap and JQuery. One important thing: we only want to avoid some scripts/css caching, not everything.

I really appreciate your help! Thanks!

Upvotes: 10

Views: 15837

Answers (1)

tao
tao

Reputation: 90287

Browser caching is the ability of a browser of storing results from remote resources. The process if fairly simple: it remembers the url the resource was requested from and the response. If, while the resource is cached, the resource is requested again, rather than making the call, the browser serves the saved copy from cache, as it saves bandwidth and time.

If you add a parameter that is always unique to a resource call, the browser will always reload it, because the parameter will be changed and the browser will assume it's a different resource.

Typically, a timestamp in either seconds (php timestamp) or milliseconds (javascript timestamp) will make sure your resource will always be reloaded:

JavaScript:

<script src id="myScript"></script>
<script type="text/javascript">
   // change path to match your file:
   let resourcePath = '/js/someScript.js';

   document.getElementById('myScript').src = resourcePath + '?v=' + Date.now();
</script>

PhP:

<script src="/js/someScript.js?v=<?=time();?>"></script>

Note: you can do the same for any other resource (.css or media resources), to disable caching. Also note you're not, technically, disabling caching - that's not so easy to do and differs from browser to browser. You are allowing caching but you're always requesting a different resource, because it has the bogus parameter which keeps changing (and which could be renamed from v to anything else, for example, to ?no-cache=).

Upvotes: 13

Related Questions