Skip to content

okadots/masonry-wp-lazy-load

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

masonry-wp-lazy-load

I spent copious hours googling for a way to implement lazy load with a gallery generated by Advanced Custom Fields that was using Masonry (this is on Wordpress) to no avail.

I found lots of info on how to integrate infinite scroll, but this was only for a list of posts (the posts are ajaxed in from the "next" page of posts), but nothing about doing this with just a gallery of images.

And then my amazing co-worker had a solution.

Lazy load works by having a placeholder image until the time that the actual image is needed.  The image url is stored in a data attribute in the image tag.

Masonry lays out the page after all of the images have been loaded - and doesn't fire again after that.

So if you are using a generic placeholder graphic that is always the same size... how will masonry know how to lay out the images properly as they appear on scroll??

The solution to this is to get the height and width of the image you wish to load and make them attributes (or a style) on the image tag itself. Yes it's terrible to have inline styles, but it's necessary in this case.

One of the challenges of Advanced Custom Fields Gallery plugin is that it doesn't use wordpress attachments for images, so you can't just call for the width and height using wp_get_attachment_image_src.  Even just asking ACF to retrieve the size doesn't work because we aren't using the original image, but one of the crops that wordpress automatically creates (in this case a custom size added with "add_image_size").  ACF was consistently returning the size of the original image and not of the custom thumbnail size I had created. 

The solution to this was to use php getimagesize() to return the proper values of the specific image size I was looking for. 

Once the placeholder image has been given the size of the image you are loading -- it successfully holds the place (har har) of the not yet loaded image. And ta-dah! you have a beautiful lazy loaded masonry style gallery.

Maybe you already knew how to do this, but maybe this will also help someone who didn't know how to do it and this will save them many hours.

About

Using Masonry and Lazy Load for a WP ACF Gallery

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published