Explain Codes LogoExplain Codes Logo

How to force a web browser NOT to cache images

html
cache-control
http-headers
web-development
Anton ShumikhinbyAnton Shumikhin·Aug 13, 2024
TLDR

The quick solution: attach a query string (such as a timestamp) to the image URL, thus making each request unique and bypassing cache.

<!-- Who needs cache when we have timestamps? --> <img src="image.jpg?nocache=<?= microtime(); ?>" alt="Non-cached Image">

Make sure to replace <?= microtime(); ?> with the appropriate function for your server language to generate a timestamp.

Quick query string hack

The idea behind this is simple – whenever you change something in the URL, the browser treats it as a new request and fetches the resource again. So appending the current time as a parameter ensures the URL is unique for every request. Smart, right?

You could say it's the web development equivalent of "This is not the image you're looking for..."*. Kind of like a Jedi mind trick for your browser.

Getting strict with headers

HTTP headers, specifically Cache-Control, provide more control over the caching behavior. Let's play good cop, bad cop with your browser.

Cache-Control: no-cache

Good cop: The no-cache directive forces your browser suspect to check with the server before using a cached resource.

Cache-Control: no-store

Bad cop: The no-store directive is stricter – it tells the browser not to store any part of the request or response. It's the equivalent of "You have the right to remain uncached!"

The case of stubborn caching

Modern browsers are like stubborn mules sometimes; they may ignore these cache control techniques if they seem inconsistent or if caching would lead to a better user experience.

To make sure your instructions are heeded, complement your Cache-Control headers with an HTTP Expires header set retroactively.

Example:

/* Time travel! Set date in the past to make the request stale on arrival */ Expires: Wed, 21 Oct 2015 07:28:00 GMT

Power up with dynamic image names

Consider changing the filename for each image update. Now browsers have to pick up the most recent version. It's like changing your disguise every time the nosy families move into your neighbourhood 🕵️‍♀️.

Test all the things!

Test these methods in varied environments. Corporate or public proxies might be throwing a spanner in your cache control plans. Be kind, remember they just want to make browsing faster.