Version links to CSS and JS

Most web apps use cascading style sheets (.css files) and javascript (.js files). There's a pitfall regarding such files that occurs when you update your app.

Most browsers will cache .css/.js files. When you update your app, the browser will likely use the old, cached versions of these files, and not the new ones. That's usually not desirable, since you usually have updates that you need your users to see. If you do nothing, then, in the new world, users will see a mix of new web pages with old css/js. That's bad.

As a programmer, you know that you can hit Control + F5 (or similar) to refresh everything, and the app will look fine. But that's dangerous, because now you see one thing, but most of your users will still see broken pages. You never want to force your users to hit Control + F5.

Here's a simple way of getting around this problem. Just append a version parameter to each link to a css/js file:

<link rel="stylesheet" href="../css/styles.css?ver=27" media="all">
Every time you release a new version of your app, you increment the value of this version parameter. The version parameter has no other role than to make the URL different between different releases. This will force the browser to fetch the newest version of the css/js file when a release is made, and avoid the browser cache.

Of course, you need to define the value of this version parameter in one place. A natural home for it is web.xml:

  <context-param>
   <param-name>ver</param-name>
   <param-value>27</param-value>
  </context-param>

You reference such data in a JSP like so:

<link rel="stylesheet" href="../css/styles.css?ver=${initParam.ver}" media="all">

You may want to centralize this policy in a .tag file:

<link rel="stylesheet" href="../css/styles.css<tags:ver/>" media="all">
ver.tag:
<%@ include file="/WEB-INF/TagHeader.jspf" %><%@ tag pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>?ver=${initParam.ver}