Thursday, September 1, 2011

Versioning JavaScript Files

A common problem web developers face is dealing with versions of JavaScript files (and other resources like CSS file, images etc.)  On the one hand we want to cache the file so that it doesn't get downloaded every time, but on the other hand we need to be able to force the browser to get a new version if the file changes.

My solution is to treat my own JavaScript files differently from the files I include from frameworks such as jQuery.

For framework files I add a version number to the file name e.g. jQuery-1.5.1.min.js. When the framework is updated, I will use a new file with the new version number in its name and the browser will fetch the new file.

For my own files I append a query string to the end of the url that contains a version number. This version number is fetched from the DLL that the controller code runs from. The effect is that each time a new build is deployed, the browser will refetch the JavaScript file, but in between builds it will cache it.

To this end I have two different URL helpers that I use when referencing files as seen below.

<script type="text/javascript" language="javascript" src="<%: Url.Content("~/Content/Scripts/jquery-1.5.1.min.js") %>"></script>
<script type="text/javascript" language="javascript" src="<%: Url.VersionedLink("~/Content/Scripts/General.js") %>"></script>