Trick: Prevent Image Caching of Dynamic Images

For the longest time I’ve been struggling with an issue of browsers caching dynamic images that have the same name. Here’s my use case:

A user has a profile photo on their profile photo that’s called MyProfilePhoto.jpg. The user uploads a new image for their profile photo. When they load their profile page, the browser sees the request for MyProfilePhoto.jpg and just pulls from cache. But in reality, the image has changed. This causes the user to re-upload the photo and get super frustrated. The solution seems to be stupidly simple: Append a random querystring value.

So my new image source value is something like: MyProfilePhoto.jpg?r=1234

This causes the image to be reloaded every time the page is loaded. Another way that I’ve thought about attacking this and making it a little more controlled is to store a random value to the database when a new image is uploaded and just append that value to the querysting. This will ensure that the new image is always loaded, and that it will pull from cache until the image changes.

I’m just lazy, and don’t want to add more fields into my user tables =)

You can see this in effect on my profile page on bodymod.org. Just view the source of my profile image.

.: Adam

Discussion Area - Leave a Comment