0

Is anyone able to determine, how to stop the jQuery caching the image that it grabs, and displaying the same image around and around again?

Basically the image is been re-uploaded every 5 seconds, as it acts as a webcam (if you check the time stamp on the bottom right of the image, you can tell if it's been updated or not)

http://colourednoise.co.uk/scripts/index.htm

Thank you

(sorry I forgot to hit paste for the code)

$(function(){
$(document).ready(function() {
    var imgs = ['http://www.ramseycommunityradio.co.uk/images/webcam.jpg', 'http://www.ramseycommunityradio.co.uk/images/webcam.jpg']
    $("#webcam").attr('src', imgs[1]);
    var refreshId = setInterval(function() {
        $("#webcam").fadeOut("slow", function() {
            var $el = $(this);
            $el.attr('src', $.inArray($el.attr('src'), imgs) === 0 ? imgs[1] : imgs[0]);
            $el.fadeIn("slow");
        });
    }, 2000);
});
James Lawson
  • 409
  • 4
  • 14

3 Answers3

5

You could try appending a changing query string onto the URL, this should stop caching if that is indeed your problem. I've seen this done with a time stamp here: how to generate and append a random string using jquery

So each time you generate an image you do:

var qs = (new Date).getTime();
var url = 'http://www.example.com/images/myimage.jpg?' + qs;
$(el).attr('src',url);
Community
  • 1
  • 1
n00dle
  • 5,949
  • 2
  • 35
  • 48
2

your code:

var imgs = ['http://www.ramseycommunityradio.co.uk/images/webcam.jpg', 'http://www.ramseycommunityradio.co.uk/images/webcam.jpg']
    $("#webcam").attr('src', imgs[1]);
    var refreshId = setInterval(function() {
        $("#webcam").fadeOut("slow", function() {
            var $el = $(this);
            $el.attr('src', $.inArray($el.attr('src'), imgs) === 0 ? imgs[1] : imgs[0]); 
// this condition is redundant, it will ultimately give the same result always
// because imgs[0]==imgs[1]

            $el.fadeIn("slow");
        });
    }, 2000);

as far a JQuery is concerned you are not changing the SRC attribute (JQuery knows nothing about the content of the image). Try using two different names in the server-side like webcam0.jpg and webcam1.jpg and alternating between them.

Matanya
  • 6,233
  • 9
  • 47
  • 80
  • This hit the nail on the head! Took me a minute or two to see what was going on but it now makes sense. Thank you :-) – James Lawson Dec 14 '12 at 13:11
1

One trick is t append a random query string URL which causes the image to reload from the server. The code could be something like:

setInterval(function() {
    var img = $("#img").get(0);
    img.src = img.src.replace(/\?.*/, "") + "?" + Math.random();
}, 5000);
Salman A
  • 262,204
  • 82
  • 430
  • 521