Preloading images using JQuery- Load images from folder?
Currently I am using a pretty basic function to pre-load images:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
I have a fairly large number of small images I need to pre-load (all far under 1MB when combined), and was wondering if there was a way to do so without declaring each image individually.
Any ad开发者_JS百科vice would be greatly appreciated!
You could use a loader-script like supplyJS. This is pretty useful, when loading lots of "smallish" images, because it's much faster.
Demo: http://www.typeofnan.com/lab/mxhr-stream/
The loading would look like:
supply.listen('image/jpg', function(payload, filename) {
jQuery('<img>', {
src: 'data:image/jpeg;base64,' + payload
}).appendTo(document.body);;
});
supply.setDealer('/cgi-bin/supply.pl').files({
images: [
'/images/foo.jpg',
'/images/bar.jpg',
'/images/another.jpg'
]
});
This example would directly append the newly loaded images to the document.body
. Of course you could do anything with those in the mime-type-listener.
Admittedly, this also requires to specify each image explicitly but it should be a whole lot faster.
..and by the way, perhaps the author of supplyJS will add a *.jpg for instance, because that's actually a great idea ;)
Not really a direct answer to your question, but a suggestion I have is to consider using CSS sprites, that is put them all in one image and control what is displayed using CSS.
精彩评论