I am trying to create a simple animation viewer for a sequence of map images using Javascript. I first load the images into a global array like this
while( datetime <= endDatetime)
{
var fname = getImgFnameFromDate(datetime);
var imgAdd = new Image();
imgAdd.src = fname;
imgStore.push(imgAdd);
datetime.setMinutes(datetime.getMinutes() + 15);
}
and then loop through them with a short wait between each image.
function iter()
{
++imgIndex;
if (loopFlag) imgIndex = imgIndex % imgStore.length;
document.getElementById("map").src=imgStore[imgIndex].src;
}
Now, the maps are made in near real time and occasionally some will be missing. The file fails to load giving instead a broken link image in the midst of the animation. I would like to simply skip an image that did not load, either by skipping over it or removing it from the array.
I have tried using the image width attribute as a proxy for ‘isLoaded’ i.e. something like
function iter()
{
++imgIndex;
if (loopFlag) imgIndex = imgIndex % imgStore.length;
document.getElementById("map").src=imgStore[imgIndex].src;
if (imgStore[imgIndex].width == 0) iter();
}
However this is unreliable and often leads to an infinite loop as it appears to trigger before the images have had a chance to load.
I have tried specifying an onError function for the images, but I can’t work out what that function should do. I really want some kind of isLoaded attribute, rather than an event. Maybe I’m going about this the wrong way?
You can set a flag on the image object when it loads and test that flag later:
Then elsewhere, you can check to see if the image has been loaded yet:
When using an onload handler, just make sure that you set it before you set the
.srcproperty otherwise, there are some cases in some browsers where you will miss the onload event if the image is already in the browser cache.An alternate approach (perhaps simpler to use) would be to have a second array that only contains loaded images and your main code only uses that:
Then, your code that uses
imgStorewill only ever see images that are actually loaded. One downside to this is that images go intoimgStorein load order, not necessarily in the order that you request them so the order this way could be different than your old way.