Layman's Guide to Image Lazy Loading in Lightning

Submitted by Barrett on Sun, 06/16/2019 - 10:08

I was pleasantly surprised earlier this week to discover how easy it is to lazy load images in Lightning*.

Lightning ships with the Blazy module, which integrates the javascript library of the same name. Accomplishing lazy loading of images is as easy as changing the display widget to use the Blazy formatter. As a test, I set up a content type with an image Media field on my local environment, set the Media entity up to use Blazy, and created a View to display all the content.

With the formatter set, images are only loaded when they are within a configurable distance of the display window. The impact, as you can see in the screenshot below, is that with Blazy enabled initial page load makes 3 image requests, load time is just over half a second, and transfers about 5K. When scrolling the page, images are loaded in as they approach the viewport.

Screenshot of page and web inspector network traffic with lazy loading enabled.
Screenshot of page and web inspector network traffic with lazy loading enabled.

With normal, full content loading, the page makes 19 image requests, the load time is roughly 4 seconds, and the transfer size is 600K (my source images are pretty small).

Screenshot of page and web inspector network traffic using normal loading.
Screenshot of page and web inspector network traffic using normal loading.

Limitations

The 1.x branch of Blazy, which is what Lightning ships with, does not work when embedding Media through CKEditor nor when using the CKEditor image embed option. There is a "Blazy With Media" formatter option in Lightning. I've not played with it but it may resolve at least the first issue. The 2.x branch of Blazy also apparently supports Media oEmbed and has an input filter for inline images.

Footnote

Ironically, I don't actually use Lightning on this site, a fact which I expect I'll get some grief about from the folks at work, and which, perhaps, I'll reconsider at some point. Nor do I have Blazy enabled, though I expect I'll be changing that in short order also.