Skip to content

Instantly share code, notes, and snippets.

@ZiTAL
Last active January 5, 2016 13:13
Show Gist options
  • Save ZiTAL/913cd85e4979476754a6 to your computer and use it in GitHub Desktop.
Save ZiTAL/913cd85e4979476754a6 to your computer and use it in GitHub Desktop.
javascript: preload images and launch callback
var images_array =
[
'https://upload.wikimedia.org/wikipedia/commons/3/3b/Paris_Tuileries_Garden_Facepalm_statue.jpg',
'https://img.imgur.com/iWKad22.jpg',
'https://this_image_not_exist'
];
var loadImages = function(arr, callback)
{
var count = 0;
var images = [];
for(var i in arr)
{
images[i] = new Image();
images[i].onload = function()
{
console.log(this.src+" image loaded");
count++;
};
images[i].onerror = function()
{
this.setAttribute('data-error', 'true');
console.log("error loading "+this.src+" image");
count++;
};
images[i].src = arr[i];
}
var loop = function()
{
if(count===arr.length)
{
var tmp = [];
for(var i in images)
{
if(images[i].hasAttribute('data-error')===false)
tmp.push(images[i]);
}
callback(tmp);
}
else
{
window.setTimeout(function()
{
loop();
}, 0);
}
};
loop();
};
loadImages(images_array, function(images)
{
console.log(images);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment