Howdy adaptable designer tangelo!

: Clippy, bash / zsh commands, CSS Color

Intersection Observer

lazy-loading example

HTML (note: 1x1px spacer gif as src)

<img class="lazy-img"  src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-src="lazyDog.jpg">
<img class="img lazy-img" ... >

JS:

const ioOpt = {
    // root: null,
    // threshold: 0.2
}

const ioCallback = (entries, observer) =>{
    entries.forEach( entry => {
        const img = entry.target;

        if( entry.intersectionRatio > 0 ){
            img.src = img.dataset.src;
            observer.unobserve( img );      
        }
        
    } );
} 

const observer = new IntersectionObserver( ioCallback, ioOpt);

const targets = document.querySelectorAll(".lazy-img");
targets.forEach( target => {
    observer.observe(target);
} );

Notes:

  • Options: if root ist omitted or null, the viewport is used as the root element
  • Options: threshold 0.0 – 1.0 how much (percentage) of the target hast to be intersecting with the root to fire the callback
  • To know if the content is above or below, compare if entry.boundingClientRect.y is greater/lesser than entry.rootBounds.y.