A key benefit of working with the web (or more specifically http) is it’s native ability to cache. This can be ‘tuned’ to make websites extremely fast and slick, especially after initial page load.
In addition, if you use a popular CDN to serve up common files (e.g. jQuery etc) then you could benefit from a user already having that file in their local cache, from another website; thus your site appears faster, thanks to this file having already being downloaded – sweet!
I love caching and where possible, always enable it.
But What Happens when you change a file?
The obvious answer, is to rename your file. But of course, you then have to rename all references to this file, within your website – not ideal!
‘Who you gonna call…..” Ok…don’t worry, I won’t go there, far too cheesy!
For a long time, I used Microsoft’s own Bundling and Minification solution, which for the record, I still think is excellent. However, when it comes to cache-busting, the Microsoft solution, resolves this by appending a unique query-string to the end of the file.
For example: a file called ‘styles.css’ could become ‘styles?v=r0sLDicvP58AIXN’
This solutions works well, in the sense that it certainly provides a ‘new’ file name – but on my travels I have subsequently learnt, that the query-string method is not the best accepted practice for cache-busting, and can fail under certain circumstances.
An Alternative Approach
I use the excellent MiniBlog framework for my blog site, and love the way it deals with caching and cache busting (amongst other things).
MiniBlog (and no doubt others) take an approach of actually changing the path as against the filename. This path is created, based on a time stamp (or specifically, time-ticks) and is remarkably simple. It’s now my preferred method of cache-busting.
Firstly, you need to create a c# class, that will be responsible for creating the unique new path to any given file.
In the below example, you may note that this class also allows for the use of a CDN path, in which the cache-bust would not be required.
The key to the unique path creation is the File.GetLastWriteTime syntax – this literally establishes the last time a file was changed, and uses that, as a basis to create a unique numerical value of time-ticks.
Of course, we will need to somehow establish the real path, as to where the file is located (as against this virtual one); in short, we need some routing.
This is very easily done, with the below code snippet added to the web.config file – using some regex wizardry, this tells incoming requests, that when it comes across one of these ‘special paths’, to route it to the correct location.
Finally, to actually use the cache-busting feature in your page, just path your appropriate links and scripts (css, js etc) using the below method.
Making changes to any of the files within the project, will clearly demonstrate a new path on a refresh.
Give it a go - it certainly works for me!