jQuery each() and load() ordering

2019-07-24 07:23发布

问题:

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

回答1:

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.



回答2:

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