Do browsers cache images?

I have a PHP page with some Javascript that changes the SRC attribute on a IMG tag after a fixed interval of time (5 seconds). There is a fixed number of images that I cycle through. The PHP builds a string array for all the image URLs. The images are small most less than 10k.

How can I tell if the browser is caching the images and if not what must I do to ensure that a browser does cache them?

4

2 Answers

Yes the browser will cache them, often even when your headers say otherwise. I have found the best combination is to issue the necessary Cache-Control headers along with appending a random string to the source URL.

Example, set the max age in seconds:

header("Cache-Control: max-age=3600"); 

Then append a random string to your img sources. This will need to be in Javascript, not in PHP because once your URLs are generated in PHP they won't keep updating with a new random string:

var randomString = "" + new Date().getTime(); var imageUrl = yourImageArray[someIndex] + "?" + randomString; 

Hope you get the idea.

3

If you need to try to force the browser to not cache certain images, you should properly configure the headers the server is sending for each image request such that they send the proper Cache-Control headers.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like