Deploying a web application with changed files
The last weeks I ran a few times against the same old problem again and again. We made a new version of our web application and deployed it on our server. Our clients logged in to the application, and the look ‘n feel looked like crap. The problem was that the browsers of our clients were still caching the images and stylesheets of our old application. We got a lot of calls and mails stating that there was a problem and each time we had to explain them that they had to clear the cache of their browser.
This started me to look at a possible solution to cover this common problem. There is no javascript that’s capable of clearing the cache of a browser. This is due to some security constraints. But I found a nice and easy solution for our problem.
When the user calls a page from our application, we read a cookie that contains the last known version of our application. This version is compared with the installed application version. If both are different, it means that our application is upgraded or downgraded, and the user has to clear the cache of his browser. If this is the case, we show an alert box with instructions of how to do it.
After installing this quick fix, we didn’t receive any calls anymore. It is an easy to implement solution that solves a lot of frustration at developers side: “Why is the user dump? He should know that he has to clear the cache!”.
----- Javascript code behind it -----
// Helper function to create cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
// Helper function to read a value from a cookie
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[ i ];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
// Function called to check if an upgrade has happened.
// The value passed to this function is the current version of your application.
function upgrade(newVersion) {
var oldVersion = readCookie("our_application_version");
var upgradeMessage = "You have upgraded to a new version (" + newVersion + "). "
+ "It is important to clear the cache of your bowser before continueing.\n\n"
+ "If you are using Firefox, go to \"Tools\" > \"Clear Private Data...\". Only check \"Cache\" in the options list and press the \"Clear Private Data Now\" button.";
if(oldVersion != null && oldVersion != newVersion) {
createCookie("our_application_version", newVersion, 365);
alert(upgradeMessage);
} else {
createCookie("our_application_version", newVersion, 365);
}
}