I have an image and I want to automatically update it using either javascript, jquery or ajax.
Until now I have the following code.
<html>
<head>
<script language="JavaScript"><!--
function refreshIt() {
if (!document.images) return;
document.images['myCam'].src = 'swt.png';
setTimeout('refreshIt()',50); // refresh every 50ms
}
//--></script>
</head>
<body onLoad=" setTimeout('refreshIt()',50)">
<img src="swt.png" name="myCam">
</body>
</html>
I think it is not working because the browser is caching the image and it is not updating the image correctly.
Can someone provide me a working example?
This will do the trick, but it's a nightmare as far as performance.
<html>
<head>
<script language="JavaScript">
function refreshIt(element) {
setTimeout(function() {
element.src = element.src.split('?')[0] + '?' + new Date().getTime();
refreshIt(element);
}, 50); // refresh every 50ms
}
</script>
</head>
<body>
<img src="swt.png" name="myCam" onload="refreshIt(this)">
</body>
</html>
Just add a random number to the query string on every refresh. This will trick the browser into thinking this is a different resource, while the server will serve the same picture.
On top of loading a different image each time and increasing the refresh time, you should start the setTimeout
again after the image has fully loaded.
function refreshIt() {
if (!document.images) return;
var img = new Image();
img.src = 'swt.png'; // use a random image
img.addEventListener('load', function () {
// you should cache the image element
document.images['myCam'].src = this.src;
setTimeout(refreshIt, 50); // refresh every 50ms
}, false);
}
}
You are setting the image source to the same string. That will not refresh the image, the browser thinks it already has that image, and won't issue another request. Try adding a random query parameter each time you want to refresh - then the browser should see the image as different resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With