Auto Ad Code

Thursday, July 8, 2010

Image Update Issue (Cache)

Another common issue with developers is that sometimes they don't see an updated Image or may be flash file no matter they have changed the file at Server.
For example a developer is showing default.jpg as display image in any forum application but even when user changes his/her display image they still see the previous image as display image. Whats the problem here? though Image on server has been replaced successfully. Actually problem is with browser cache that browser has cached the image having name default.jpg for that path and whenever browser sees that path it picks image from cache instead of server.
Okay so whats the solution?
Solution is pretty much simple and straight which is to include some random string at the end of image path
for example the following image tag can create the cache issue
<­im­g s­rc=­"images­/­default­.­jpg­"­/­>
to over come the cache issue simply add any random string(starting from ? like query string) after .­jpg
i.e. following image tag will never create the image cache issue
<­im­g s­rc=­"images­/­default­.­jpg­?­6453426­"­/­>

To make this dynamic one can assign the source for image tag from Server side code and can make use of Random class to append some number after the jp­g. In this case you will have to add runat="server" and assign some id to image tag or you can simply use the asp:image tag and the ImageURL property. Let us suppose we are having imgTst and we are assigning src from serverside to avoid the cache issue.
Over code will be like this

VB

Randomize()
Dim mRnd As Random = Nothing
Dim mRandomNumber As Integer = mRnd.Next(0, 99999) 'This will generate any Random number from 0 to 99999
imgTst.src = "images/default.jpg?" & mRandomNumber

and if imgTst is asp:Image then our code will be like

Randomize()
Dim mRnd As Random = Nothing
Dim mRandomNumber As Integer = mRnd.Next(0, 99999) 'This will generate any Random number from 0 to 99999
imgTst.ImageUrl = "images/default.jpg?" & mRandomNumber

C# (C Sharp)

VBMath.Randomize(); //You can skip this
Random mRnd = null;
int mRandomNumber = mRnd.Next(0, 99999);
//This will generate any Random number from 0 to 99999
imgTst.src = "images/default.jpg?" + mRandomNumber;

and if imgTst is asp:Image then our code will be like

VBMath.Randomize();  //You can skip this
Random mRnd = null;
int mRandomNumber = mRnd.Next(0, 99999);
//This will generate any Random number from 0 to 99999
imgTst.ImageUrl = "images/default.jpg?" + mRandomNumber;


Same technique can be applied for flash files (having extension flv, fla) or fpr any file for which we wan to avoid the cache issue

1 comment:

  1. Thanks for this. I can't tell you how long I looked for this resolution to this caching issue, and your was perfect

    ReplyDelete