Tuesday, February 3, 2009

How to prevent browser caching : TechPitcher

How to prevent browser caching : TechPitcher: "
How to prevent browser caching

There are many ways you can prevent browser caching.
One of them is to include following meta tags, place these tags in head section of html document.
view plaincopy to clipboardprint?

1. <META HTTP-EQUIV='Pragma' CONTENT='no-cache'>
2. <META HTTP-EQUIV='Expires' CONTENT='-1'>

<META HTTP-EQUIV='Pragma' CONTENT='no-cache'>

For ASP pages use following script at the extreme beginning of the page
view plaincopy to clipboardprint?

1. <% Response.CacheControl = 'no-cache' %>
2. <% Response.AddHeader 'Pragma', 'no-cache' %>
3. <% Response.Expires = -1 %>

<% Response.CacheControl = 'no-cache' %>
<% Response.AddHeader 'Pragma', 'no-cache' %>
<% Response.Expires = -1 %>

In case of JSP pages use following code
view plaincopy to clipboardprint?

1. <%
2. response.setHeader('Cache-Control','no-cache');
3. response.setHeader('Pragma','no-cache');
4. response.setDateHeader ('Expires', -1);
5. %>

response.setDateHeader ('Expires', -1);

If you are generating your response in java or some other languages then you need to set following parameters in response header.
view plaincopy to clipboardprint?

1. response.addHeader('cache-control', 'no-cache');
2. response.addHeader('pragma', 'no-cache');
3. response.addHeader('expires', '-1');

response.addHeader('cache-control', 'no-cache');
response.addHeader('pragma', 'no-cache');
response.addHeader('expires', '-1');

All of the above method works on the response of the particular page and tell browser not the cache the response.

There is another way of telling browser to make a fresh request and don’t use the cached content for the page if any. This is done by appending some random characters to requested url. Below is sample code
view plaincopy to clipboardprint?

1. <script>
2. var url = 'http://techpitcher.com';
3. url += '?preventCache='+ Math.floor(Math.random()*100000);
4. </script>

var url = 'http://techpitcher.com';
url += '?preventCache='+ Math.floor(Math.random()*100000);

This will create a random url every time and won’t allow browser to use cache content."

No comments: