A small JavaScript image lazy loading library with Intersection Observer

io-lazyload is an extremely fast JavaScript library for lazy loading images that uses IntersectionObserver API to handle image position detection. IntersectionObserver is a fairly new web API that makes lazy loading images extremely easy. How easy is to to lazy load with IntersectionObserver? You can do it in about ≈20 lines of code if you don’t need a polyfill.
javascript-lazy-load-images


Libraries

Load the following libraries on page.

 <!-- intersection observer polyfill -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>
   <!-- the iolazy load library -->
    <script src="dist/js/iolazy.min.js" defer></script>

HTML

Add the class of lazyload to the image(s) you wish to lazyload and
modify the src attribute to read data-src

<img data-src="img/image.jpg" alt="your alt text" class="lazyload" >



JS

Initialize the script before the closing body tag (or in your own JS file)

<script>
document.addEventListener("DOMContentLoaded", function () {
    new IOlazy();
});
</script>

lazy load all images with the class ‘lazy’

<script>
  document.addEventListener("DOMContentLoaded", function () {
    new IOlazy({
       image: '.lazy'
    });
});
</script>
<!-- lazy load all image elements -->
<script>
  document.addEventListener("DOMContentLoaded", function () {
    new IOlazy({
       image: 'img'
    });
});
</script>

See live demo and download source code.

DEMO | DOWNLOAD

This awesome plugin is developed by cdowdy. Visit their official github repository for more information and follow for future updates.


One Reply to “A small JavaScript image lazy loading library with Intersection Observer”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.