Loading and preloading thumbnails is a commonly requested task in jQuery. Loading thumbnails sequentially requires the use of a progressive timer which delays the execution of each fading effect for a given time span. The rest is pretty simple.
We have a series of thumbnails:
<div id="thumbs">
<figure>
<img src="1-thumb.jpg" alt=""/>
</figure>
<figure>
<img src="2-thumb.jpg" alt=""/>
</figure>
<figure>
<img src="3-thumb.jpg" alt=""/>
</figure>
<figure>
<img src="4-thumb.jpg" alt=""/>
</figure>
</div>
We need to show a spinner before displaying each thumbnail. I'm going to dynamically attach an animated GIF to each thumbnail block with jQuery. This kind of image must be initially hidden:
#thumbs .loader {
display: none;
}
With jQuery the fading routine is as follow:
- Create an incremental time span (
i
) counter. - Attach a spinner to each
figure
block. - Loop through the thumbnails.
- Hide them.
- Create a delay with
setTimeout()
by incrementing the counter by 800 on each loop. - Fade in the spinner with a speed equal to 1/4 of 800.
- Hide the spinner.
- Fade in the thumbnail.
Here's the jQuery code:
var preload = function() {
var i = 0;
$('figure', '#thumbs').each(function() {
var $figure = $(this);
var loader = '<img src="loading.gif" class="loader"/>';
$figure.append(loader);
});
$('img', '#thumbs').not('img.loader').each(function() {
var $img = $(this);
var $loader = $img.next();
$img.hide();
setTimeout(function() {
$loader.fadeIn(i / 4, function() {
$(this).hide();
$img.fadeIn(200);
});
}, i += 800);
});
};
preload();
You can see the demo on this page.