Friday 27 December 2013

Web application client side caching

This is a very important aspect to understand that how the browser caching works and when and how to control it. I will discuss a few basic things here about the client side caching.

You can enable or disable browser caching of your web pages by specifying following tag in your application's web.config file:

 <system.web>
          <caching>  
 <outputCache  enableOutputCache="false" >  
 </outputCache>
 </caching>
 </system.web>

If you want more control over caching behavior than you should specify it in the page itself. By specifying the caching inside the webpage you can control browser caching at the page level.

Add a page directive to your webpage like this:

<%@ OutputCache Duration="1" NoStore="true" VaryByParam="*" %>

All the three attributes in this directive are required. Here we can specify the duration for which the page should be cached by setting the Duration attribute. The duration is considered in milliseconds.
With attribute VaryByParam you can specify when the page should make a fresh request. If '*' is mentioned for this attribute value that means for each parameter value in the request query string the browser will make a fresh request, if the value of any parameter changes in subsequent request.
For example if i make two subsequent request as:
http://blogger.com?id=121&tag=abc
http://blogger.com?id=122&tag=abc

In both the cases above the browser will make fresh request because the parameter value for 'id' has changed.
If you want the browser to make a fresh request on the change of particular parameter then you can specify it like, VaryByParam="tag".

By setting the value of NoStore you can specify whether you want the browser cache that page or not.

Here is a very tricky point in browser caching that you must remember or it may give you great headache at times and that is, as per the w3c standards the GET requests are always cacheable whether the caching is enabled or disabled. So whenever you are making request from javascript and do not want the page to be cached, make sure that you are making POST request.