如何解决缓存提供的javascript文件的问题? [英] How to solve problem with javascript files served from cache?
问题描述
更新服务器端代码(与JavaScript相关)后,旧的JavaScript文件将从缓存中提供.
When server side code is updated (related to JavaScript) the old JavaScript files are served from cache.
我需要一个解决方案,将旧的JavaScript文件更新为新版本.服务器上的文件更新后,需要使浏览器缓存(与JavaScript相关)失效.
I need a solution where the old JavaScript files get updated to their newer versions. Browser cache (related to JavaScript) need to be invalidated once the files on server are updated.
对于这个问题,我有以下解决方案.
I have got the following solution to this problem.
var randomnumber=Math.floor(Math.random()*10000);
var scriptfile='http://www.whatever.com/myjs.js?rnd='+randnumber;
但是我只需要在JavaScript文件进行某些更新而不是在每次页面重新加载时清除缓存.
But I need to clear cache only when there is some update on the JavaScript files not on every reload of the page.
推荐答案
大多数站点(包括堆栈溢出)为此使用其版本控制系统中的修订号:
Most sites - including Stack Overflow - use a revision number from their version control system for this:
var scriptfile='http://www.whatever.com/myjs.js?rnd='+revision_number;
每当修订版本更改时,浏览器都会指向新的" JavaScript文件.
whenever the revision changes, the browser gets pointed to a "new" JavaScript file.
您也可以手动执行此操作,方法是在某个位置的中央位置指定版本号,然后将该版本号添加到每个脚本调用中.当您更新JavaScript的一部分时,只需增加版本号即可.
You can do this manually as well, by specifying a version number at a central place somewhere, and adding that version number to every script call. When you update a part of the JavaScript, you simply increment the version number.
第三种方法是检查所包含的JavaScript文件的上次修改"时间,并根据该时间构建时间戳:
A third approach would be checking the "last modified" time of the JavaScript files you are including, and building a timestamp from it:
var scriptfile='http://www.whatever.com/myjs.js?version=20100803';
但是这将需要服务器端脚本,并且可能对于每个页面请求而言都太昂贵了.
but that would require server-side scripting and may be too expensive to do on every page request.
这篇关于如何解决缓存提供的javascript文件的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!