How to Force a Web Browser Not to Cache Images

How to force a web browser NOT to cache images

Armin Ronacher has the correct idea. The problem is random strings can collide. I would use:

<img src="picture.jpg?1222259157.415" alt="Sample Image">

Where "1222259157.415" is the current time on the server.

Generate time by Javascript with performance.now() or by Python with time.time()

Disable cache for some images

A common and simple solution to this problem that feels like a hack but is fairly portable is to add a randomly generated query string to each request for the dynamic image.

So, for example -

<img src="image.png" />

Would become

<img src="image.png?dummy=8484744" />

Or

<img src="image.png?dummy=371662" />

From the point of view of the web-server the same file is accessed, but from the point of view of the browser no caching can be performed.

The random number generation can happen either on the server when serving the page (just make sure the page itself isn't cached...), or on the client (using JavaScript).

You will need to verify whether your web-server can cope with this trick.

How to prevent browser image caching?

Just put a random parameter at the end of the image URL. A timestamp can also be used very well for this.

For example in PHP:

"http://domain.com/img.png?t=" . time();

The browser will always load this image new. You should use it with care though, it will make loading times slower.

Prevent browser from caching images

Try putting a random variable on the end of the url

http://www.test.com/images/123.jpg?{{rand()}}

Force browser to only cache images (not scripts and links)

If you don't have access to the Apache configuration itself, you can try setting expiration rules via an .htaccess file. Contrary to popular belief, not only Rewrite rules, but any Apache configuration rules can be contained there … if the Apache config allows it. But, it's worth giving it a try.

To only cache certain files, you can use a directive like:

<FilesMatch "\.(ico|pdf|jpg|png|gif|js|css)$">
Header set Cache-Control "max-age=172800, public, must-revalidate"
</FilesMatch>

(You can remove those extensions you don't want to cache, and add others.)

Now, as for CSS and JS, it is generally recommended to do the following: Instead of changing the file name itself, simply change the references to theses files by adding a (meaningless) query string to them.

For example, when embedding a JS file, do it like this:

<script src="/path/to/file.js?rev=123" type="text/javascript"></script>

Next time you update that file, simply increment the rev number.

How to prevent browsers from caching an image?

Another alternative would be to add a random string after your image file.

<img src="/path/to/image/image.jpg?<?php echo time(); ?>/>

This should ensure that the image is reloaded each time the page is displayed.



Related Topics



Leave a reply



Submit