Based on the new information that you just want to add them in order as soon as they are ready, you can do that like this
$(document).ready(function () {
// preload all the images as fast as possible
var imgs = [];
$('.fancybox').each(function () {
// get all images preloading immediately
// so there is the best chance they are available when needed
var img = new Image();
imgs.push(img);
img.onload = function() {
addReadyImages();
}
img.className = "cls";
img.src = $(this).attr('href');
});
function addReadyImages() {
// show all images that are ready up to here
while (imgs.length && imgs[0].complete === true) {
// append the loaded image from the start of the array
$('.mag').first().append(imgs[0]);
// remove the one we just did from the start of the array
imgs.shift();
}
}
});
Working demo: http://jsfiddle.net/jfriend00/sCHws/
This algorithm works as follows:
- Start preloading all the images as soon as possible.
- Store the image objects in an array in the order that the
.fancybox
items are encountered in your page
- Set an onload handler for each image so we know immediately when it's ready
- In the onload handler for any image, append all images at the front of the array that are ready and then remove them from the array
P.S. I've assumed there is only one .mag
item and thus we don't need to make separate copies of the image objects (much more efficient that way - rather than creating new image objects). If that is not the case, then please disclose your HTML so we can see the whole problem.