Ок, немного изменим пример:
function randomInt( min, max ) {
return Math.floor( Math.random() * max + min );
}
function getItem() {
var width = randomInt( 150, 400 );
var height = randomInt( 150, 250 );
var imageUrl = 'http://lorempixel.com/' + width + '/' + height + '/nature';
return imageUrl;
}
function preloadimages(arr) {
var newimages = [], loadedImagesCounter = 0;
var arr = (typeof arr != "object")? [arr] : arr
var callback = function() {}
function imageloadpost() {
loadedImagesCounter++
if (loadedImagesCounter === arr.length){
// alert("All images have loaded (or died trying)!")
callback(newimages);
}
}
for (var i = 0; i < arr.length; i++) {
newimages[i] = new Image();
newimages[i].src = arr[i];
newimages[i].onload = function() {
imageloadpost()
}
newimages[i].onerror = function() {
imageloadpost()
}
}
return {
done: function(cb) {
callback = cb || callback
}
}
}
var totalImages = 10;
var imageNames = [];
for (var imgIndex=0; imgIndex < totalImages; imgIndex++)
{
imageNames.push(getItem());
}
preloadimages(imageNames).done(function(images) {
// images are loaded
// call Mansory here
console.log('Loaded images: ' + images.length);
for (var i = 0; i < images.length; i++)
{
console.log('Image: src=' + images[i].src + ', ' + images[i].width + 'x' + images[i].height);
}
})