简体   繁体   中英

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 advice 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 ;)

并不是您问题的直接答案,但我的建议是考虑使用CSS Sprite,即将它们全部放在一个图像中并控制使用CSS显示的内容。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM