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:
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:
but that would require server-side scripting and may be too expensive to do on every page request.