Sunday, September 8, 2013

Dealing with Browser Cache


Did you try clearing the browser cache?, we often hear this when something doesn’t work in a web application. I believe most of developers know why we need to clear browser cache? or why do browsers need to do caching if it’s not such a good thing to do?

Browsers have in-built mechanism of caching webpages including all its supporting files (e.g. javascript, images or css style sheets) to avoid downloading the same content again and again. This greatly enhances the page loading speed, reduced network traffic and server load. This will work just fine until you modify a file (e.g. a javascript) and upload it on server and browser still picking up old file from its cache. In this case functionality related to this new change may not work. It can be easily fixed by clearing the browser cache but is not an ideal solution especially if you have a large audiences. 

You can also tell browsers not to cache a particular file or reduce the period they keep it cached. There are guidelines as to what type of files should be cached and what shouldn’t be cached (e.g. pages that interact with database and are updated regularly should never be cached). Disabling caching completely may degrade the overall page loading experience.

What is the idea way to handle it?
Whenever you modify a js or css file, you can tell browse that it’s a new file by putting a fake parameter in file name. e.g.

src=”scripts/jquery/jquery-1.7.1_min.js”
src=”scripts/jquery/jquery-1.7.1_min.js?version=1.1”

In each subsequent changes you need to just change the parameter value to something different. E.g.
src=”scripts/jquery/jquery-1.7.1_min.js?version=1.2”

You may find it tedious to change all references every time you modify a js file. To overcome this make the parameter value dynamic by using resource file and bean message (you can look for equivalent of 'bean message' if you are using language other than jsp).

<script type="text/javascript" src="scripts/jquery/jquery-1.7.1_min.js?version=<bean:message bundle="mybundle" key="js.jquery.version"/>"></script>

So every time you modify a javascript file, make sure you update its version/fake param value so that you never have to ask users to clear the browser cache! :-)


Happy coding!

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I hope you are able to share some of the "amazing inventions" in future logs. Click here to learn more!!

    ReplyDelete