I’m a big fan of EWWWIO for WordPress and Masonry. But lately, I’ve noticed some issues when using them together. Masonry recommends using a companion plugin called imagesLoaded to detect when an image is completely downloaded into the browser window. That allows you to run a function to trigger the re-layout of Masonry. Well, on this project, Masonry was failing even after all the images were downloaded and visible.

I didn’t verify this, but my hunch is that it has to do with how the Lazy Load component of EWWW works; it may even have to do with the fact that I’m using webp versions of images.

Whatever the reason, I found a perhaps more elegant version of triggering Masonry. We can hook into the DOM event that Lazy Load puts out when an image is revealed, and then re-trigger Masonry!

Here’s the code:

//Define the set of images you want to display using Masonry
var $gallery = $('.project-gallery').masonry({
		  itemSelector: '.image-item',
		  percentPosition: true,
		  columnWidth: '.image-item',
		  gutter:0,
		});

//Listen for lazyunveilread and trigger masonry re-draw 
document.addEventListener('lazyunveilread', function(e) {           
     $gallery.masonry('layout');
});