Information Systems



Preload images in javascript

It's actually not that easy to do and since it involves callbacks to determine when things are loaded, it's susceptible to timing issues. The following works if you check to make sure things are loaded in the start() function.

function MediaCache()
{
this.images = {};
this.addImage = addImage;
this.complete = complete;
this.finished = false;

function addImage(name, finished)
{
var image = new Image();
this.images[name] = image;
image.src = name;
if (finished == true)
this.finished = true;
image.onload = start;
return image;
}

function complete()
{
var keys = Object.keys(this.images);
for (var i = 0; i < keys.length; i++)
{
if (!this.images[keys[i]].complete)
{
return false;
}
}
return true;
}

}