Search code examples
asp.netcachingbrowser-cacheweb-farm

Invalidating Browser Cache of Static Resources


I'm working on caching of static resources. Often when a script or style is changed, it will cause problems for people for a while until their browser decides that it is time to invalidate its cache of our file.

I am hoping to solve this problem by inserting a value on the end of all script and style tags to force the browsers to send an actual request to the server. This value should stay the same across multiple servers until a command is issued to change it. How can I generate/change this value across multiple servers?


Solution

  • you can revise static resources with a querystring or filename change. Either method should refresh on the client.

    1. querystring revving - references to "style.css" become "style.css?v=1.0"

    2. filename revving - references to "style.css" become "style-1.0.css" (have to also rename or create the file "style-1.0.css" on your server)

    I've used both methods, querystring is probably more common because you don't have to rename the file on the server.

    However, this write up, Revving Filenames: don’t use querystring, gives a good reason to use filename revving instead


    One way to implement this for querystring revving would be to store a version number in the web.config app settings

    <appSettings>
        <add key="staticResourceVersion" value="1.1"/>
        ...
    </appSettings>
    

    Then create some utility method (or call ConfigurationManager.AppSettings directly) to use inline for static resource markup, for example:

    <link rel="stylesheet" type="text/css" 
        href="/css/style.css?v=<%=Utilities.GetStaticResourceVersion() %>" />
    <script type="text/javascript"
        src="/js/script.js?v=<%=Utilities.GetStaticResourceVersion() %>"></script>