Cache dynamic images from array before page loads

2020-03-26 11:32发布

问题:

I am trying to make 4 sliding galleries but I need to preload (cache) all images behind a splash screen before displaying the images in gallery form. I have been trying to use "jPreLoader v2 - http://www.inwebson.com/jquery/jpreloader-a-preloading-screen-to-preload-images" but with no luck.

The code below is how I have been trying to preload all images from each gallery directory on to a single gallery behind jpreloader then once load complete remove the whole gallery and display each gallery at a time.

var pictures =  [
    "1.jpg",
    "2.jpg",
    "3.jpg",
    "4.jpg",
    .......,
    "30.jpg"
 ]

$(window).load(function(){

preLoad();

function preLoad(){
    var max = 30;
    var pic;
    picture = '<table id="table" style="dipslay:table;"><tr>';
    for (var i=0;i < max; i++){
        if(i < 30){
            pic = "images/art/"+pictures[i];
            appendCell(pic);
        }
        if(i < 17){
            pic = "images/street/"+pictures[i];
            appendCell(pic);
        }
        if(i < 19){
            pic = "images/doc/"+pictures[i];
            appendCell(pic);
        }
        if(i < 16){
            pic = "images/commercial/"+pictures[i];
            appendCell(pic);
        }
    };
    picture += '</tr></table>';
    $('#imageScroller').append(picture);
}

function appendCell(pic){
    picture +="<td class='image'><img class='i' src='"+pic+"'></td>";
    return;
}
});

Im not quite sure how to implement the jpreloader on a dynamic image loading loop above instead of already inserted into the dom.

$(document).ready(function () {
$('body').jpreLoader();
});

Thanks.

回答1:

Custom progress bar that updates as images are downloaded

var pictures = [
                    "1.jgp",
                    "2.jpg"
                ];

var loadedSoFar = 0;

function loaded( ) {
    // do stuff
}

function updateProgress( ) {

    loadedSoFar++;

    var newWidth = $("#progress").width() * ( loadedSoFar / pictures.length );
    $("#bar").stop( true, true );
    $("#bar").animate({ width: newWidth }, 500, function( ) {
        if( loadedSoFar === pictures.length ) { loaded() }
    });
}

for( var i = 0; i < pictures.length; i++ ) {
    var img = new Image();
    img.src = pictures[ i ] + i;

    img.onload = function( ) {
        updateProgress();
    }
}

Demo here