简体   繁体   English

用jCarousel预加载图像

[英]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. 我有以下代码,它们加载JSON提要并创建jCarousel工作所需的所有HTML。 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. 可能不是一个好的解决方案,但是您可以尝试将图像加载到隐藏div中页面上的某个位置,以便在进行ajax调用并在loadTopBanner方法中使用它们之前将其缓存。 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: 如果您确实要预加载图像,则无需将它们放在隐藏的div中-您可以使用Image对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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