views:

237

answers:

2

I want to reload an image on a page if it has been updated on the server. In other questions it has been suggested to do something like

newImage.src = "http://localhost/image.jpg?" + new Date().getTime();

to force the image to be re-loaded, but that means that it will get downloaded again even if it really hasn't changed.

Is there any Javascript code that will cause a new request for the same image to be generated with a proper If-Modified-Since header so the image will only be downloaded if it has actually changed?

UPDATE: I'm still confused: if I just request the typical URL, I'll get the locally cached copy. (unless I make the server mark it as not cacheable, but I don't want to do that because the whole idea is to not re-download it unless it really changes.) if I change the URL, I'll always re-download, because the point of the new URL is to break the cache. So how do I get the in-between behavior I want, i.e. download the file only if it doesn't match the locally cached copy?

+1  A: 

Javascript can't listen for an event on the server. Instead, you could employ some form of long-polling, or sequential calls to the server to see if the image has been changed.

Jonathan Sampson
Actually, by implementing the bayeux protocol, you sort of can listen for an event. Not sure if it's worth it for OP though.
Tatu Ulmanen
I know I need to poll; basically what I want is the simplest possible way to poll for whether the image has changed, i.e. to send an http request that says "download this image if it's been modified since the one I have", so the question is what Javascript can I use to generate that request.
David Maymudes
+1  A: 

You should have a look at the xhr.setRequestHeader() method. It's a method of any XMLHttpRequest object, and can be used to set headers on your Ajax queries. In jQuery, you can easily add a beforeSend property to your ajax object and set up some headers there.

That being said, caching with Ajax can be tricky. You might want to have a look at this thread on Google Groups, as there's a few issues involved with trying to override a browser's caching mechanisms. You'll need to ensure that your server is returning the proper cache control headers in order to be able to get something like this to work.

zombat