How to force a browser to always use the latest CSS files (using the Razor view engine)

Developing for the web can take you to dodgy situations, as is with any distributed system. Simply having a client (browser) and a server bouncing data to and fro might cause performance issues. Caching comes in to save the day, however it might also cause problems from a client (human) perspective.

Let’s say you modified your CSS files, changing your old UI into a masterpiece, and uploaded them onto the production server. Your first reaction will be to open up a browser, plop in your url, wait for the site to load, hit Ctrl-F5 a couple of times (or more) and then everything will shine and sparkle (as per design). Now, the ‘hit Ctrl-F5’ step in the above process is an assumption that all developers make, and believe that Joe, Mary and Jane will do the same.

An unsuspecting user (let’s call him Joe) opens up your page to get the latest news on snail-trailing (or whatever subject your page is treating), and he is presented with the new content, however using old (cached) CSS file versions. Joe’s reaction will be, ‘What the … ?’. You don’t want to hear that, right? You want your pages to be formatted using the latest CSS files, at ALL times, from the first page-load after an update, ignoring the cached version when a new version is uploaded and without assuming the Ctr-F5 ritual. How to do that? Very simple…

Step 1:  Use the File Class (System.IO) to retrieve the DateTime instance of the last update carried out on your CSS file/s

@{ var f = File.GetLastWriteTime(Server.MapPath(“~/Content/Site.css”)); }

Step 2: Register your CSS files, and append the DateTime‘s Ticks property (number of ticks representing the date and time of this DateTime instance) to the CSS’s file name, separated with a ‘?’, like so:

<link href=”@Url.Content(“~/Content/Site.css?”+@f.Ticks)” rel=”stylesheet” type=”text/css” />

The Ticks property of the last modified date of the CSS file will ensure that when and only when the CSS file is updated, the browser will adopt the new version, thinking that the CSS file has changed. This happens simply because the Ticks postfix will now be different after every CSS update.

That’s all!


Leave a Reply