开发者

How to solve problem with javascript files served from cache?

开发者 https://www.devze.com 2023-01-09 15:52 出处:网络
When server side code is updated (related to JavaScript) the old JavaScript files are served from cache.

When server side code is updated (related to JavaScript) the old JavaScript files are served from cache.

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;

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;

whenever the revision changes, the browser gets pointed to a "new" JavaScript file.

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.

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.


Instead of using a random number, use a version number or update timestamp, so it becomes:

var script = 'http://mysite.com/the_script.js?2010-08-02';

// or

var script = 'http://mysite.com/the_script.js?v1.20';

If you don't want to update this manually, you can either use a make script that searches for and replaces a tag with a version number:

var script = 'http://mysite.com/the_script.js?{{script_update_date}}';

// have a shell script find and replace the above {{ }} tag with the date or such 
// when deploying to production

Or if your version control system uses it (like SVN) you can have it replaced with the revision number so that it is updated when a new script is checked in.

0

精彩评论

暂无评论...
验证码 换一张
取 消