Jazz
Jazz

Reputation: 5917

No new request for a new Image with the same URL

I want to refresh an image that is regularly updated on the server, so I load it like this:

var img = new Image();
img.onload = myCallback;
img.src = imageUrl;

imageUrl is always the same, and I set these HTTP headers to force the browser to issue a new request every time I try to load the image:

Cache-Control: public,max-age=0
Expires: -1
Last-modified: Mon, 21 Nov 2008 01:03:33 GMT
ETag: 1234

But it only works on Chrome; Firefox, Opera, IE and Safari only send a request to the server the first time, then I always get the cached image.

If I add img.src = '' to myCallback, it works on Opera and IE, but still not in Firefox and Safari (I only tried Firefox 11).

I could add a random query string to my URL, but it would consume much more bandwidth, as most of the time the server replies with 304 Not modified.

Is there a way to make it work on Firefox ?

Upvotes: 1

Views: 384

Answers (2)

jches
jches

Reputation: 4527

Instead of relying on inconsistent browser and server behavior, you could make it a two-step process:

  1. Make an AJAX call to a URL that the client can use to find out if the image has been updated (force no cache on that one)
  2. If it has been updated, update the image.src with a new URL (new string appended to the base URL)

You could use something like the UNIX timestamp of the last update to the image as the random string appended to the URL.

Example using JQuery-style pseudocode (may or may not work as is):

function updateImage() {
    $.get('/HasImageBeenUpdated?', function(answer) {
       // answer could be JSON: {wasUpdated: true, newImageUrl: 'url'} 
       if (answer.wasUpdated === true) {
            $('#theImage').attr('src', answer.newImageUrl);
        }
    });
}
setInterval(updateImage, 1000); // update every second

Upvotes: 1

Riz
Riz

Reputation: 10246

To overwrite cache each time, append a random number at the end of URL as a parameter.

Upvotes: 0

Related Questions