Saturday, November 08, 2008

Caching JS (JavaScript) files

When a JavaScript file is requested through the browser such as Internet Explorer, Mozilla and Netscape, this is accompanied by HTTP header directives that tell the browser how long the resource can be retrieved directly from the browser cache as opposed to from the origin server.
Since the browser represents the cache closest to the end user it offers the maximum performance benefit whenever content can be stored there.

But this brings in a problem when the content is changed in the js file. The browser does not load the file from the server but keeps using the one from cache.

In our application, any change we make to the js file is seen at the end user's machine only after repetitive refreshing in the browser. It might take some time to load the correct file from our server. So we have found a solution to fix this problem.

Every time we do a new build (either a major revision or minor release), the timestamp of release will be always newer than older releases.
Say the timestamp for the latest release 9.07 is 19-10-2008 09:10 whereas last major release say 9.06 was 11-10-2008 09:10. Even for the next minor release, it would be 20-10-2007 09:00 or 19-10-2007 10:30.

We were then attaching this timestamp to the src attribute of the script tag. Note that we are not going to do anything with this parameter 'v' in our js script!

For example, instead of
<script type="text/javascript" src="./javascript/MyScript.js"></script>

we are going to use

<script type="text/javascript" src="./javascript/MyScript.js?v=17-10-2008at16:11:19"></script>

So every time we deploy the files, the html seeks for the file similar to MyScript.js?v=17-10-2008at16:11:19 which will be different for every release. Since the browser will not find this file in its cache, it will automatically download the file from the server.