Systematically updating src of IMG. Memory leak.
I am currently updating an image every x sec. A few ways I thought of doing this were as follows:
Take One:
var url ="...";
$('#ImageID').attr('src', url);
Now this works perfectly changes the image but causes a memory leak.
Take Two:
So it is creating DOM elements, so I attempted the following.
<div id="ImageHolder">
</div>
var image - "..."; //Obv actual image in working.
$('#ImageHolder').empty();
$('#ImageHolder').html(image);
Now this works but causes a flicker when it changes which is unliked. Now with two images and swapping them at intervals works fine, but I want to stay as low on bandwidth as possible.
Edit 1:
My Code:
<form name="selected">
<input type="hidden" name="map" />
</form>
<img id="MyMaps" src="http://localhost/web/blank.png" alt="" />
<script type="text/javascript">
var locate = window.location;
var uri = document.selected.map.value;
var MyHost = window.location.hostname;
function delineate2(name) {
totheleft= uri.indexOf("maps/") + 5;
totheright= uri.lastIndexOf("&");
return (uri.substring(totheleft, totheright));
}
function loadImage() {
var CurrentMap = delineate2(name);
var url = 'http://' + MyHost+ '/map/' + CurrentMap+ '/image?' + new Date().getTime();
$('#MyMaps').attr('src', url);
setTimeout(loadImage, 10000);
}
</script>
Has anyone done something similar and found a working solution, or how can I go about preventing the memory leak / flickering when the image updates?
I have never thought of doing this like your fist method.. interesting. I can imagine that it causes a memory leak because every single image is kept in memory because nothing is actually removed. Thats just a guess though.
I would recomend sticking to the second method but modifying it so solve the flicker, like fading between images. A good jQuery plugin to look at would be the jQuery Cycle Plugin
If that plugin doesn’t do it for you or you want to keep the code small, jQuery also has some animation functions built in. fadeIn() and fadeOut() may be of interest.
Something like this might work better.
I believe a shorter way to do this might be: (also delay() may be optional, I just put it there in case you need it.)
Additionally there may be a delay for the image to load if it hasn’t been preloaded. I’m not 100% sure how to do that off the top of my head so a quick google seach came up with this:
http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript