Search code examples
asp.netasp.net-mvchttp-caching

Output caching dynamically generated CSS


In my application the user has the option to modify the CSS of their site.

This is unlikely to change that often, but when it does we need to ensure that they, and their site visitors, see the results instantly.

We do record the date and time that the user updated their CSS so an easy solution would be to just append a timestamp to the url.

However, I would like to know if I can set the cache headers programatically to force the browser to re-request the CSS file if it changes.


Solution

  • If you include an hash to your url, ie

    http://server.example.com/styles/css.css?hash 
    

    it will get reloaded when the hash changes, because the browser will fetch it from the new url :

    Version 1:

    <style type="text/css" link="styles/css.css?hash=v1" />
    

    Version 2:

    <style type="text/css" link="styles/css.css?hash=v2" />
    

    Client caching is a client matter, let them do as they see fit : a new URL means the ressource has changed, so it will need to be reloaded. Keeping the same URL with cache control headers may lead you to a world of pain, because of varying client implementations.

    If you put cache control headers (last-modified, expires, ETAG), you cannot be sure that you CSS will get refreshed when it changes :

    • because aggressive browser (or proxy) caching may ignore those.
    • because you may serve V1 on May 1st, with an expiration date of Jun 1st, update it to V2 on May 15th, and your clients will have to wait 15 days to get the new version.

    With the url hash, the worst case scenario is that the client does not put your css in cache, but user experience is not altered, as they always get the latest version.

    With expiry date or last modified date, worst case is that the client gets an old version, and this will alter the user experience :)