This project is not covered by Drupal’s security advisory policy.
Image Lazy Loader using IntersectionObserver.
Most image lazyloaders use scrolling events to see if an image is in or near the viewport and should start loading.
However, there is a new kid in town: IntersectionObserver.
Using this to observe when an image is in or near the viewport is faster and better suited for image lazyloading because it uses less resources and has a better performance.
I wrote this module while doing Lighthouse tests on a project. I improved the score a lot by using Blazy to lazy load images.
I also tried another lazy loading Algorithm but for some reason I kept having problems with both image lazy loaders with images that were already in viewport. Or sometimes lazyloading would not trigger on load but working fine after a page refresh.
Since Lighthouse's 'Read more' about image lazyloading already urges to 'consider using an IntersectionObserver' I decided it was time to create an image lazyloader using an IntersectionObserver.
Please note that browser support is still limited (Works on Chrome, Firefox and Edge only at the time of writing). My fallback solution for now is to simply load images if IntersectionObserver is not supported.
I tested with falling back on Blazy, and it kinda worked, but decided against it to start from a cleaner code.
Installation and usage
Install the lazyload_images module as you would normally install a
contributed Drupal module:
- require the module:
composer require drupal/lazyload_images --prefer-dist
- enable the module:
drush en lazyload_images -y
- This module provides a library that you need to include on the
twig files where you want to use it:
{{ attach_library('lazyload_images/lazyloader') }}
- Finally, add the class 'js-lazyload-image' to your image.
Remove the 'src' attribute and set the 'data-src' attribute to the
desired image that should be lazyloaded:
<img data-src="mylargeimage.jpg" class="js-lazyload-image">
Or point the 'src' attribute to a very small thumbnail of the actual image.:
<img src="verysmallthumbnail.jpg" data-src="mylargeimage.jpg" class="js-lazyload-image">
This also works using drupal_image in twig to print a responsive image (picture element with sources) if you have defined a responsive image style:
{{ drupal_image(node.field_image.0.entity.uri.value, 'my_responsive_image_style', {
alt: node.field_image.0.alt,
title: node.field_image.0.title,
class: 'js-lazyload-image',
}, true) }}
Thubnails will automatically be blurred and have an unblur effect when
the image is lazy loaded.
Project information
Seeking new maintainer
The current maintainers are looking for new people to take ownership.- Project categories: Content editing experience, Media, Performance
9 sites report using this module
- Created by flyke on , updated
This project is not covered by the security advisory policy.
Use at your own risk! It may have publicly disclosed vulnerabilities.
