How to have Packery fire after LazySizes loads images

653 Views Asked by At

I am using lazysizes to lazy load my images but also am trying to use Packery and I can't figure out how to have the Packery script fire after lazysizes loads all my pictures as it won't lay out the pictures right. This is the code I have

<script>
// initialize Packery
var $container = $('#container');
// init
$container.packery({
itemSelector: '.item', percentPosition: true,
}); 
</script>

I want it to fire after lazysizes adds the class 'lazyloaded' to img class, since it replaces lazyload with lazyloaded.

<div class="card-image waves-effect waves-block waves-purple">
            <a href="#image-1"> <img data-sizes="auto" data-srcset="Photos/kirby-thumb.jpeg 350w, Photos/kirby-thumb-med.jpeg 500w, Photos/kirby-thumb-lrg.jpeg 750w" data-src="Photos/kirby-thumb.jpeg" class='responsive-img lazyload' id="thumbnail">
          </div>
          <div class="card-content blue-grey">
            <span class="card-title activator grey-text text-darken-4">Kirby</span>

          </div>
          </a>
1

There are 1 best solutions below

7
On

Unstested but in case I get your question right, it should work like this. You test if the amount (array.length) of the lazyload class (I used the default class) is the same as the 'loaded' class. You put this test in a timeout loop, so the script runs every X milliseconds to check if the condition is fulfilled. As soon as the amount is the same - you kill the timeout loop and trigger packery.

// simple test - in case your orginial selector is lazyload
// the amount of lazyload and lazyloaded has to be the same.

function testAllLoaded() {
    return ($('.lazyload').length === $('.lazyloaded').length);
}

var testDelay = 10; // timeout in milliseconds 


$().ready(function() {
    // ask until test is fullfilled...
    var $container = $('#container');
    var fire = setTimeout(function() {
        // all loaded
        if(testAllLoaded()) {
            // run packery
            $container.packery({
                itemSelector: '.item', percentPosition: true,
            });
            // kill timer
            clearTimeout(fire);
        }
    } , testDelay );

});