How to force a reload of JS and CSS files when changed

Caching of Javascript and CSS files is great and really improves performance in the browser. But caching also means that changes to the files are not picked up. So how do you get the browser to automatically reload the files when you have updated them because of new requirements, bug fixed etc.?

There are several ways to achieve this. On Apache you can for instance use the modpagespeed module that automatically changes links to resources when the backend resource files change. Other ways include manually adding a version number to your resources (?version=1234), and changing the file name of the resource.

For IBM Domino, IBM XWork Server and XPages you can of course manually change the file name of your resources when content changes (and remember to update references to those files in your code). A better method is to create your own versioning system for your resources based on the idea of adding a unique id to the link to the resources. The following describes this method.

You can add a version number to an application scoped bean and then update that version number whenever you want the browser to reload your resources. Here’s a code snippet for such a version number bean (this is only some of the stuff needed for a bean – see my blog post about creating a bean for more details) :

public class Config implements Serializable {
	private static final long serialVersionUID = 6469339826789980362L;
	private static final String version = "20130410";

	public static String getVersion() {
		return version;
	}
}

Using this bean I can then create links to my Javascript and CSS files like this:

<xp:this.resources>
	<xp:script clientSide="true">
		<xp:this.src><![CDATA[${javascript:"/jsCommon?open&v=" + config.getVersion()}]]></xp:this.src>
	</xp:script>
	<xp:styleSheet>
		<xp:this.href><![CDATA[${javascript:"/custom.css?open&v=" + config.getVersion()}]]></xp:this.href>
	</xp:styleSheet>
</xp:this.resources>

The links then look like this in the browser:

db.nsf/custom.css?open&amp;v=20130410
db.nsf/jsCommon?open&amp;v=20130410

Whenever I want to force a reload, I then update the version string in my Config bean. The resources are then reloaded.