Updating an image that periodically downloads

I have a webcam script that sends JPG via FTP every 10 seconds to my web server (overwriting the original).

How can I get jQuery to update this image? I tried:

window.onload = function() {
            $('body').prepend('<img id="cam" src="ww.jpg" alt="" />');
            setInterval(runAgain, 12500);
        };

        function runAgain() {
            $.ajax({
                url:'ww.jpg',
                cache:false,
                beforeSend:function() {
                    $('#cam').remove();
                },
                success:function() {
                    $('body').prepend('<img id="cam" src="ww.jpg" alt="" />');
                }
            });
        }

Note. I do not want to refresh the page if I can help.

+3
source share
4 answers

The dirty way is to add a timestamp or random number at the end of the src image to prevent caching, for example img src = "image.jpg? Random = [RANDOM]" where [RANDOM] is the timestamp or random number

+2
source

, - . - , , :

...
url:'ww.jpg?' + Math.random()
...

, , , .

+2

You just need to upgrade src. Of course, you should use cache bitter to avoid browser caching when destroying an image. A solution in this case would be a random query string parameter.

$(function() {
    var $img = $('<img>', {
        src:  'ww.jpg'
    }).appendTo(document.body);

    setInterval(function() {
        $img.attr('src', function(_, src) {
            return [src, '?', ~~(Math.random() * 40000)].join('');
        });
    }, 12500);
});
+1
source
function updateLogo() {
    var base_src = "http://www.google.com/logos/2011/graham11-hp-start.png";
    var logo = $('#logo');
    var timestamp = new Date().getTime();
    // uncomment the timestamp part if your server supports an extra parameter to prevent caching
    logo.attr('src', base_src);// + '?_ts=' + timestamp);
};

setInterval(updateLogo, 1000);

If your server supports an additional parameter in the image URL, you will prevent image caching.

0
source

All Articles