Chud37
Chud37

Reputation: 5007

javascript: Preload ONE image at a time

I currently have a rotating background that preloads the images when the page is loaded. However, I would like to preload the images one at a time, if that is even possible.

My code:

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

    });

The code above works fine. If there is a better way please let me know! But otherwise how can I just preload one image at a time?

Upvotes: 1

Views: 1193

Answers (1)

Andreas
Andreas

Reputation: 21881

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

Upvotes: 2

Related Questions