how to clear or replace a cached image

If you're writing the page dynamically, you can add the last-modified timestamp to the URL:

<img src="image.jpg?lastmod=12345678" ...


<meta> is absolutely irrelevant. In fact, you shouldn't try use it for controlling cache at all (by the time anything reads content of the document, it's already cached).

In HTTP each URL is independent. Whatever you do to the HTML document, it won't apply to images.

To control caching you could change URLs each time their content changes. If you update images from time to time, allow them to be cached forever and use a new filename (with a version, hash or a date) for the new image — it's the best solution for long-lived files.

If your image changes very often (every few minutes, or even on each request), then send Cache-control: no-cache or Cache-control: max-age=xx where xx is the number of seconds that image is "fresh".

Random URL for short-lived files is bad idea. It pollutes caches with useless files and forces useful files to be purged sooner.

If you have Apache and mod_headers or mod_expires then create .htaccess file with appropriate rules.

<Files ~ "-nocache\.jpg">
   Header set Cache-control "no-cache"
</Files>

Above will make *-nocache.jpg files non-cacheable.

You could also serve images via PHP script (they have awful cachability by default ;)


Contrary to what some of the other answers have said, there IS a way for client-side javascript to replace a cached image. The trick is to create a hidden <iframe>, set its src attribute to the image URL, wait for it to load, then forcibly reload it by calling location.reload(true). That will update the cached copy of the image. You may then replace the <img> elements on your page (or reload your page) to see the updated version of the image.

(Small caveat: if updating individual <img> elements, and if there are more than one having the image that was updated, you've got to clear or remove them ALL, and then replace or reset them. If you do it one-by-one, some browsers will copy the in-memory version of the image from other tags, and the result is you might not see your updated image, despite its being in the cache).

I posted some code to do this kind of update here.


Change the image url like this, add a random string to the querystring.

"image1.jpg?" + DateTime.Now.ToString("ddMMyyyyhhmmsstt");

I'm sure most browsers respect the Last-Modified HTTP header. Send those out and request a new image. It will be cached by the browser if the Last-Modified line doesn't change.