Avoid Javascript/Css caching

做~自己de王妃 提交于 2020-06-25 21:38:08

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/50276601/avoid-javascript-css-caching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!