In our application we have two use cases in which we want to avoid retrieving an out-of-date image from the browser cache:
- A user changes her profile picture.
- A user changes the picture of another users she is allowed to manage (think of a team and their captain).
In the upload view, we don’t have any problem by appending a timestamp to the image URL, as already suggested in other questions (Refresh image after AJAX file upload, Break image caching). For all other views, there might be a problem with that simple approach: we actually want to use the cache where possible, but avoid it, if we know that we have recently updated the image.
In our application, an administrative user uses a userlist which represents users by their user image (I know, this is revolutionary). If she has just changed one of the user images, she wants this list to show the new image. Same for every other time she sees the user’s image.
We cannot add ?timestamp={now} to every image in this user list, because this would destroy the benefit of any caching.
Any recommendations for a good approach that uses the cache as much as possible and reloads images that we know we have updated?
The solution we have chosen for now:
Part 2 may need some explanation: Fortunately we use a very good JS framework on the frontend that allows us to define arbitrary methods and use them in templates. Our models have one method that returns the photo URL and this URL is used in every template.
When uploading a new image, we associate the id with the current time stamp in localStorage:
Whenever we request an image path, we look into localStorage to see whether we have to append a timestamp to the URL, otherwise the URL is returned as is.
Advantages / Improvements
localStoragefor every image URL we are building. This may be expensive.Code
The code to generate the URL looks like this
In API (very simplified)
The template code remains the same: