Lazyload - markhowellsmead/helpers GitHub Wiki

Images

Say Hello logic

Reworked 6.3.2025. So much easier and more reliable! Only use where the old image loading logic is still in place. Replace the old lazysizes script with this version. No HTML modifications necessary.

const showImage = figure => {
    if (!figure || !figure.querySelectorAll('img').length) {
        return;
    }

    figure.classList.add('o-lazyimage--loaded');

    figure.querySelectorAll('img').forEach(image => {
        if (image.getAttribute('data-srcset')) {
            image.setAttribute('srcset', image.getAttribute('data-srcset'));
            image.removeAttribute('data-srcset');

            if (image.getAttribute('data-sizes')) {
                image.setAttribute('sizes', image.getAttribute('data-sizes'));
                image.removeAttribute('data-sizes');
            }

            image.classList.add(
                'lazyautosizes',
                'o-lazyimage--loaded',
                'o-lazyimage__image--lazyloaded'
            );
        }
    });
};

const observer = new IntersectionObserver(
    entries => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                showImage(entry.target);
                observer.unobserve(entry.target);
            }
        });
    },
    {
        rootMargin: '0px',
        threshold: 0.1,
    }
);

document.querySelectorAll('figure.o-lazyimage').forEach(figure => {
    observer.observe(figure);
});

Lazysizes

https://github.com/aFarkas/lazysizes

No initialization necessary. Use data-src and/or data-srcset and add the lazyload CSS class.

bash

npm install lazysizes --save-dev

JavaScript

require('lazysizes');