jQuery each() and load() ordering

此生再无相见时 提交于 2019-12-11 03:54:02

问题


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



来源:https://stackoverflow.com/questions/10898365/jquery-each-and-load-ordering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!