javascript:一次预加载一张图片

时间:2013-01-25 12:57:39

标签: javascript jquery

我目前有一个旋转背景,可在页面加载时预加载图像。但是,如果可能的话,我想一次预加载一个图像。

我的代码:

function preload(arrayOfImages) {
        $(arrayOfImages).each(function(){


            $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
        });
    }
    $(document).ready(function () {

    var b = [<? $img = getContents(ROOT."/img/backgrounds/");
            foreach($img as $i)
            {   echo "\"" . $i . "\"";
                if($i != end($img)) echo ",";
            }
        ?>];
    preload(b);

    var r=Math.floor(Math.random()*b.length)
    $('#bg1').css("background-image", "url('/img/backgrounds/"+b[r]+"')");

    var alt = false;
    var delay = 50000;
    var speed = ((delay / 3)*2);
    var opacity = 1;

    setInterval(function() {
        var r=Math.floor(Math.random()*b.length);

        //put the individual preload code here

        switch(alt)
        {   case true:
                $('#bg1').css("background-image", "url('/img/backgrounds/"+b[r]+"')");
                $('#bg1').fadeTo(speed,opacity);
                $('#bg2').fadeOut(speed);
            break;
            case false:
                $('#bg2').css("background-image", "url('/img/backgrounds/"+b[r]+"')");
                $('#bg2').fadeTo(speed,opacity);
                $('#bg1').fadeOut(speed);
            break;
        }
        alt = !alt;
        }, delay);

    });

上面的代码运行正常。如果有更好的方法请告诉我!但是否则我怎样才能一次预加载一个图像?

1 个答案:

答案 0 :(得分:2)

function preload(arrayOfImages, index) {
    index = index || 0;

    if (arrayOfImages && arrayOfImages.length > index) {
        var img = new Image();
        img.onload = function() {
            console.log(arrayOfImages[index] + " loaded successfully");
            preload(arrayOfImages, index + 1);
        };
        img.src = arrayOfImages[index];
    }
}

fiddle