Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve problem with javascript files 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.

like image 956
Dora Avatar asked Aug 02 '10 08:08

Dora


2 Answers

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.

like image 174
Pekka Avatar answered Sep 20 '22 21:09

Pekka


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.

like image 20
Jesse Dhillon Avatar answered Sep 22 '22 21:09

Jesse Dhillon