1
var image1 = new Image();
image1.src = someUrl;

// someUrl is a valid URL to a PHP file which outputs a PNG file using the imagepng function. This action caches image1 to someUrl.

image1.onload = function() {

    // Some things have changed and a new image is created, which I would like to cache to someUrl.
    // This is currently done by sending a session (temporary) cookie, which is recognised by the PHP file, so that it knows to take different action than the first time.
    // Again, the imagepng function is used to output the image.

    var image2 = new Image();
    image2.src = someUrl; // this is the exact same URL
};

The desired result is to have the browser cache the image2 as a replacement of the cached image1. Unfortunately, image1 is the one that is cached, even after the image2.src = someUrl; statement.

What does work, however, is to cache image1, then create the session cookie and manually go to the someUrl page. It then does cache image2.

Is it not possible to make a browser cache an image twice, without refreshing the page?

3
  • depends on what caching headers you set. when you load image2 add a last-changed header with the current timestamp. this will invalidate the first one. but again, this depends on the cache settings you set for your first image Commented Jun 6, 2013 at 15:22
  • @TheBrain which headers do you recommend for both images? Commented Jun 6, 2013 at 15:23
  • A new image should have a different URL to ensure downloading. Or you would need to send a no-cache header with the first download (though I'm not sure how browsers do handle this if both images are used on the same page). Commented Jun 6, 2013 at 15:26

2 Answers 2

5

You can try adding arbitary params to the url. For example :

var image1 = new Image();
image1.src = someUrl;

var image2 = new Image();
image2.src = someUrl + '?action=cache'; // or timestamp

This will trick the browser to treat image2 as a new image, while still loading the image from the correct url (Assuming you aren't sending any other paramaters in GET, in that case use '&' instead of '?')

Sign up to request clarification or add additional context in comments.

Comments

0

Try using cache control headers in your php file which outputs the png. E.g.

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

source: http://php.net/manual/en/function.header.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.