javascriptjqueryqueuejquery-masonryimagesloaded

Maintaining masonry item order with images


I'm having trouble keeping the order of my masonry items, since they all have images that load at different times. All of my items are processed in an ordered way and for each one I run this line to add them:

$('#grid').append($div).imagesLoaded(function() {
    $div.show();
    $('#grid').masonry('appended', $div, true);
    $('#grid').data('masonry').layout();
});

The problem is that each div has an image that loads for a random amount of time, so the div with the first image loaded goes to the front (out of the usual order).

I know jQuery has some queuing functions, but I'm not sure exactly how to apply them here.


Solution

  • So, I ended up using queues. I've changed the individual function to

    $('#grid').queue('items', function( next ) {
        $('#grid').imagesLoaded(function() {
            $div.show();
            $('#grid').masonry('appended', $div, true);
            $('#grid').data('masonry').layout();
            next();
        });
    });
    

    After each set of elements added, I simply call

    $('#grid').dequeue('items');
    

    and this seems to solve the sorting problem for now.