I would like to have images, css, and javascript cached client-side on their browser when they load up a web page. There are so many different types of caching I am confused as to which ones to use with asp.net mvc.
Would it also be possible to have their browsers check for new or modified versions of these files?
Thanks!
Unless you've messed with your server, yes it's cached. All the browsers are supposed to handle it the same. Some people (like me) might have their browsers configured so that it doesn't cache any files though. Closing the browser doesn't invalidate the file in the cache.
@Logan: Yes, the browser caches images automatically, provided your server sends the necessary headers to tell the browser it's safe to cache it.
You need to set cache control headers on the server. You can do this by sticking this in your web.config:
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
</staticContent>
</system.webServer>
This would tell the browser now to even check for new content on anything static for 30 days.
For your second question, provide some mechanism of adding a querystring to the content. In my current project we compress and combine and javascript and css as part of the build. When putting links in the page is looks like:
<script src="/Resources/Javascript/Combined.js?v=2.2.0.1901" type="text/javascript"></script>
The querystring is the Major.Minor.0.Changeset number and changes anytime we push a build, causing the client to re-fetch it. The same exact thing happens on stylesheets in their <link>
element.
Browsers take care of this for you automatically, actually. You have to go out of your way to get them to NOT cache css, js, html and images.
I'm not that familiar with ASP MVC, but I think they type of caching you're thinking of is opcode caching for your created dynamic output server-side?
@Paul Creasey and @Salsa are both correct that browsers will handle caching by default so long as the link is the same.
As you mentioned, this raises a problem when you need to update those files as you have no guarantee that the client's browser will check for an updated version. In many cases they only do this after a fixed amount of time has passed which can create a crummy user experience.
There are a number of questions already asked on this site as to how to handle alerting the client browsers to refresh the cache. In short, they all rely on changing the link when you change the file's contents.
You can append a parameter to the URL that will only be used for caching purposes such as:
<script src="/myJavascript.js?version=4"></script>
Then just change the version number when you change the contents and need to force a client side refresh ala this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With