简体   繁体   中英

Preload images with jCarousel

I have the following code which loads a JSON feed and creates all the HTML needed for the jCarousel to work. However, I'm not sure how to preload the images. Anyone have any idea's how to do this?

$(".banner ul").jcarousel({
    itemLoadCallback:loadTopBanner,
    auto: 6,
    wrap: 'circular',
    scroll: 1,
    animation:1000,
    itemFallbackDimension:10
});

function loadTopBanner(carousel, state){
    $.getJSON("get_top_banner.php", function(data){
        carousel.size( data.length );
            $.each(data, function(i){
                carousel.add(i, makeTag(this.imageURL, this.URL));
            });
        });
    }

function makeTag(img, url){
    return "<a href='" + url + "'><img src='" + img + "'></a>";
}

This should do the trick, however, it is untested, and can be further optimised:

function loadTopBanner(carousel, state) {
    $.getJSON("get_top_banner.php", function(data) {
        carousel.size(data.length);

        // make array of elements to which load events can be attached
        var imgs = [];

        $.each(data, function(i) {
            var img = $("<img/>").attr("src", this.imageURL);
            imgs.push(img);
        });

        // init a load counter
        var loadCounter = 0;

        $.each(imgs, function() {
            $(this).one("load", function() {
                loadCounter++

                // when all have loaded, add to carousel
                if (loadCounter == data.length) {
                    $.each(data, function(i) {
                        carousel.add(i, makeTag(this.imageURL, this.URL));
                    });
                }
            });
            if(this.complete) $(this).trigger("load");
        });
    });
}

May not be a good solution but you can try to load the images somewhere on the page in a hidden div so that they will get cached before you make a ajax call and use them in loadTopBanner method. This way the carousel will not show any delay in loading the images.

If you really want to preload images, you don't need to put them in a hidden div -- you can use the Image object:

var image = new Image();
image.src = "images/foo.jpg";

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