RDX
RDX

Reputation: 165

Loading and appending images progressively

I have an issue I can't get over. I made a simple jQuery album gallery and I have this function:

function loadAlbum (index) {
    for (var j=1; j < xmlData[index].length; j++) {

        var img = new Image();

        $(img).load(function() {
                    $(this).hide();
                    $('#album'+index+' .photoContainer').append(this);
                    $(this).fadeIn();
                })
                .error(function(){
                    //alert("Could not load one or more photo!");
                })
                .attr({
                    'src': xmlData[index][j],
                    'id': 'img'+index+j,
                    'class': 'photoFrame',
                    'width': newW,
                    'height': newH
                })
                .css({
                    'width': newW,
                    'height': newH
                });
    };
};

Now, as you can see all the images src's are imported from an external XML file containing the data (images names are progressive ex.:photo001.jpg, photo002.jpg and so on).

They are created in the DOM trough a for loop and appended to a div.

What's the issue you may say ? I need all images to be appended in a progressive way as specified on the XML data but this happens only on the local computer and not if uploaded on some server. I figure out that this is due to the different loading time of each image depending on size... but I still can't figure out how to work this around. Does anyone have any idea?

Upvotes: 3

Views: 2112

Answers (1)

Dimitry
Dimitry

Reputation: 6603

The following attempts to load one image at a time. Once an image is loaded, the next in the set is loaded afterward.

function loadAlbum(index) {
    var i = 0;
    var j = xmlData[index].length;
    function loadImage() {
         if (i >= j) return;

         // do what you're doing in the loop except for ....
         $(img).load(function() {
             $(this).hide();      
             $('#album'+index+' .photoContainer').append(this);
             $(this).fadeIn();
             // increments i by 1 and calls loadImage for the next image.
             i++;
             loadImage();
         // etc.
    }
    loadImage();
}

I leave it as an exercise for you to determine how multiple images can be loaded at once and still maintain the ordering :)

Upvotes: 6

Related Questions