使用jCarousel预加载图像

Preload images with jCarousel

本文关键字:图像 加载 jCarousel 使用      更新时间:2023-09-26

我有以下代码,它加载JSON提要并创建jCarousel工作所需的所有HTML。然而,我不知道如何预加载图像。有人知道怎么做吗?

$(".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>";
}

这个应该可以达到这个效果,但是,它还没有经过测试,可以进一步优化:

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");
        });
    });
}

可能不是一个很好的解决方案,但你可以尝试加载图像在页面的某个地方在一个隐藏的div,使他们将得到缓存之前,你使ajax调用和使用它们在loadTopBanner方法。这样,carousel在加载图像时就不会显示任何延迟。

如果你真的想要预加载图像,你不需要把它们放在一个隐藏的div中——你可以使用Image对象:

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