I have two code snippets with me
// Code Snippet One
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
});
}
preload([
'img/One.jpg',
'img/Two.jpg',
'img/Three.jpg'
]);
// Code Snippet Two
function preload(arrayOfImages) {
$(arrayOfImages).each(function () {
$('<img />').attr('src',this).appendTo('body').hide();
});
- How do I use the code to make sure the images have preloaded before using them?
- How to fire a notification that says all images have been preloaded. Any new jQuery 1.8 functionality that I can use here?
- What’s is the difference between Code Snippet One and Two. Which to use when?
A fiddle example is most appreciated
Here’s how I am trying to load the preloaded images in a div (image-gallery)
setTimeout(function() {
$('.image-gallery').each(function(){
// what to put here?
});
}, 2000);
The first example will create an image element in memory and change its src to point to your image to be preloaded. The problem is that some browser (versions) do not start to load the images unless they have been added to the DOM. That’s what snippet two is doing.
In both cases you could add a
.load()event handler to the jQuery image object to specify a callback for when the respective image has been loaded.Try to use a counter. You increase the counter in each .load() handler and if it reached your image count, all images have finished loading.
EDIT: Change snippet two like this
And call it like this