Caching of static files
We had a caching problem at work awhile back, and I wanted to detail our solution here and see what people think.
The problem was with javascript files, stylesheets, and static xml files. At the time we were updating our web application nearly everyday, so were adding/editing these files pretty consistently. When people would log in, they wouldn’t see the changes in these files, because the browser was caching them, especially if the styles or javascript were not inline.
Now, in other places in our application, we would append the current date to some urls in order to make sure the user would get a fresh copy of the page, by appending the date to the url, it guaranteed that the browser wouldn’t have a cached page that matched that url. We couldn’t simply use that same technique for these files however, because we WANTED them to be cached, but we also wanted them to be updated as soon as a new one showed up on the webserver. So what we did was add a “BuildID” key into our web.config file, and added a “BuildID” property to our base page class. Everytime that we included a script, stylesheet, or xml file, we would append “?BuildID=<%=BuildID%>” to the url of the file. Now everytime that we make updates to the files, we increment the BuildID variable in the web.config so that the browser will see a new url for the files, and grab the updated copies.
Heres an example:
<script type=”text/javascript” src=”commom.js?BuildID=<%=BuildID%>” ></script>
This has worked out perfectly for us, the files get cached, and when we update the files, we never have people who don’t get the new copies!
This seems kind of hacky, but it works, what do you think?
Anonymous said,
Wrote on March 11, 2005 @ 5:20 am
Does seem kind of hacky, but I don’t deal with static files that change more than twice a year so I’m not sure what the solution would be. Too bad we can’t stuff page directives into static files and cache them based on parameter like we can aspx pages.
Anonymous said,
Wrote on March 11, 2005 @ 10:13 am
I don’t think its a hack; it seems natural to me. Its similar to changing the filename to reflect the file version, but with a site-wide BuildID you move everything forward when there is a single change to the site. Appending the current date to the URL was pretty bad