If you have enabled expiry headers, entity tags, etc. (and even if not), anyway most of the browsers have enabled cache. But how can we force client browser to load new version of JavaScript file or CSS static file? Especially if you did a change in any site specific static file. File from browser cache can broke behavior of website or/and design. So how to tell browser to load updated static file?
Solution is quite simple – put dynamic parameter in source URL. For Example: <script src=”/Scripts/site.js?v=1”… With each file change – we should change parameter value. Browser will see source URL as different and load updated JavaScript or CSS. Now the question is how to automate this process. My suggestion is to put web app assembly revision number as a version of static files, which content might be changed. Basically make solution DLL version number dynamic and put this number as a parameter to static files source URL.
Now step by step.
First we need to make version number of solution DLL dynamically changed on each build. Open AsseblyInfo.cs file:
And instead of last 0 in version number put *:
[assembly: AssemblyVersion("1.0.0.*")]
Last number in assembly version is revision number and now it will be different on each build.
Next let’s create assembly helper which read this and returns this number:
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Kitsula.Helpers { public class AssemblyHelper { public static string CurrentVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.Revision.ToString(); } } } }
Now we can use helper to retrieve the number and use it as version variable value. Examples:
<link rel="Stylesheet" type="text/css" href="@Url.Content("~/Content/CSS/Site.css")?v=@AssemblyHelper.CurrentVersion"/>
<script type="text/javascript" src="@Url.Content("~/Scripts/Site.js")?v=@AssemblyHelper.CurrentVersion"></script>
Note: Don’t forget to put reference to assembly namespace at the top the view: @using Kitsula.Helpers