2

I have a script that loops through a series of JSON objects that represent images, the loop loads an image and once it has been loaded it appends it to an element on my website/application.

The images are in the correct order in the JSON however they are appearing in different orders depending on the images that load the quickest because they are appended first. I want to make sure that whatever order the images load, they are always in the correct order (The order that the loop denotes).

The method I'm hoping to end up with allow me to access the style of the wrapping anchor before the image is loaded to show a loading icon also.

Here's the part of the script that I am talking about:

$.each(project.images, function (index, image){

var image_src = '<?= IMAGE_PATH ?>library/preview/'+ image.file_name;
var image_markup = $('<img class="new-image" />').attr('src', image_src)
                                                     .load(function(){

    if (this.complete) 
    { 
        var anchor_markup = $('<a href="javascript:void(0)" class="image-anchor" data-image-index="'+ index +'" id="image-index-'+ index +'">');
        $(anchor_markup).append(image_markup);
        globals.markup.image_slider.append(anchor_markup);
        $('.new-image').fadeIn(200).removeClass("new-image");
    }
});
});

The example can also be seen at http://www.staging.codebycoady.com/work

Alex
  • 8,353
  • 9
  • 45
  • 56

2 Answers2

5

If you want them in the correct order just append them without waiting for them to load, hide them and then in the onload callback toggle them visible.

JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
  • Apologies, but I'm struggling to work out how to order the functions for what you have suggested, could you please elaborate further? – Alex Jun 05 '12 at 14:02
  • Actually, by taking `var anchor_markup = $(...);` and `globals.markup.image_slider.append(anchor_markup);` out of the call back and putting them both before it, I think I have fixed it. – Alex Jun 05 '12 at 14:07
1

If you want images to appear in correct order then you should listen on load event of images and once an image is loaded you mark it (in some array/object) it's loaded. And then you show all images that are marked as loaded from the beginning (i.e. when 1,2,3 are loaded and 4 is not, then you set display block on 1,2,3, even if 5 was just loaded).

Nux
  • 9,276
  • 5
  • 59
  • 72