lazyload

lazyload is a little bit of JavaScript (826 bytes) that tries to polyfill lazy loading support for <img> elements, <picture> elements, and CSS background images.

If lazy loading is natively supported already, lazyload will know and get out of the way.

lazyload on GitHub

Demo

To best demonstrate how images lazy load, they need to be very far away from the bottom-edge of your browser’s viewport, so … start scrolling (please, and thank you).

Oh, also, if you'd like to see them load lazily:

  1. Crack open your browser’s dev tools
  2. Choose the Network tab
  3. (optional, but nice) Filter by Img/Image(s) to see only images
  4. Notice that each image isn’t requested until it’s near the bottom-edge

Demo #1: An <img> element with src and srcset

A pretty marsh
<img data-lazy-src="src-srcset-1024x768.jpg"
     data-lazy-srcset="src-srcset-2048x1536.jpg 2x"
     loading="lazy" alt="A pretty marsh" width="1024" height="768" />

Demo #2: An <img> element with src, srcset, and sizes

A pretty marsh
<img data-lazy-src="src-srcset-sizes-512x384.jpg"
     data-lazy-srcset="src-srcset-sizes-1024x768.jpg 1024w,
                       src-srcset-sizes-1536x1152.jpg 1536w,
                       src-srcset-sizes-2048x1536.jpg 2048w"
     sizes="100vw" loading="lazy" alt="A pretty marsh" />

Demo #3: A <picture> element with src and srcset

A pretty marsh
<picture>
  <source data-lazy-srcset="picture-1024x768.jpg,
                            picture-2048x1536.jpg 2x"
          media="(min-width:768px)">
  <img data-lazy-src="picture-768x576.jpg"
       data-lazy-srcset="picture-1536x1152.jpg 2x"
       loading="lazy" alt="A pretty marsh" />
</picture>

Demo #4: A CSS background-image

<!-- HTML: -->
<div class="custom-class-here lazy-bg"></div>

/* CSS: */
.lazy-bg {
  background-image: none !important;
}

Add lazyload to your project

  1. Install it: npm i @theoutfit/lazyload --save
  2. Import it: import lazyload from '@theoutfit/lazyload'
  3. Call it: lazyload()
  4. Adjust your code:
    • change every img element’s src attribute to data-lazy-src
    • change every img element’s srcset attribute to data-lazy-srcset
    • add a loading="lazy" attribute to every img element
    • add a lazy-bg class to every element with a background-image
    • add this rule to your CSS:
      .lazy-bg {
        background-image: none !important;
      }

Learn more

Questions / issues / improvements

If you have any questions, if you’ve discovered an issue, or if you can think of any improvements, please let us know:

lazyload Issues

Brought to you by