DEV Community

Cover image for Lazy loading images using Intersection-Observer API - JavaScript
ayka.code
ayka.code

Posted on • Edited on

Lazy loading images using Intersection-Observer API - JavaScript

IntersectionObserver is a build-in JavaScript API, It can give you more control over HTML elements and events! It provides an easy way to asynchronously observe changes related to any HTML element.

In this Blog post i will introduce you to the IntersectionObserver API by building a lazy-loading images functionality which is very important functionality when it comes to making your website more user-friendly .

show sticky navigation before leaving the header by ..px : Intersection Observer API

We will create three horizontally images that will load from an external website, But! at the first time we load the page, we will load a gray image in each img attribute, than, when we scroll down the page, and when we are close to an image by 200px than the intersectionObserver will load the real image, So, the HTML code goes like this :

<html>
  <head>
    <link rel="stylesheet" href="style.css" />
    <script defer src="script.js"></script>

  </head>
<body>
   <div class="features">
  <img
          src="https://besthqwallpapers.com/Uploads/25-6-2020/137048/berry-pie-pastries-sweets-wild-berries-cake-with-berries.jpg"
          data-src="https://besthqwallpapers.com/Uploads/25-6-2020/137048/berry-pie-pastries-sweets-wild-berries-cake-with-berries.jpg"
          alt="Computer"
          class="features__img lazy-img"
        />

  <img
          src="https://tastemade.club/wp-content/uploads/2019/09/fruit-pie-recipes-inspirational-mixed-berry-pie-recipe-of-fruit-pie-recipes.jpg"
          data-src="https://tastemade.club/wp-content/uploads/2019/09/fruit-pie-recipes-inspirational-mixed-berry-pie-recipe-of-fruit-pie-recipes.jpg"
          alt="Computer"
          class="features__img lazy-img"
        />

  <img
          src="https://lilluna.com/wp-content/uploads/2018/05/Berry-Pie-7.jpg"
          data-src="https://lilluna.com/wp-content/uploads/2018/05/Berry-Pie-7.jpg"
          alt="Computer"
          class="features__img lazy-img"
        />

  </div>


</body>
</html>

Enter fullscreen mode Exit fullscreen mode

*Now lets make them more beautiful! *

.features {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;

  align-items: center;
  gap: 8rem;
  margin: 0 12rem;
}

.features__img {
  grid-column: 2 / 4;
  width: 100%;
}


img {
  transition: filter 0.5s;
}

.lazy-img {
  filter: blur(20px);
}
Enter fullscreen mode Exit fullscreen mode

show a section on scroll + transition animation using the IntersectionObserver API

Now we reach the most excited part! we will start using the IntersectionObserver API!

First, Let’s start by selecting every image that contains data-set named “src” (data-src) :

// Lazy loading images
const imgTargets = document.querySelectorAll('img[data-src]');
Enter fullscreen mode Exit fullscreen mode

next, we will let our intersectionObserver API observe every selected image :

...
const imgObserver = new IntersectionObserver(loadImg, {
  root: null,
  threshold: 0,
  rootMargin: '200px',
});
// observer every selected image
imgTargets.forEach(img => imgObserver.observe(img));
Enter fullscreen mode Exit fullscreen mode

now let’s build the loadImg() function before the imgObserver constant.

complete project

We will check if the Observer API is intersecting any selected image and if it is! than we will replace the src img with the data-src attribute (changing the gray image with the real image).
after that we will add an event listener to check if the image has been loaded or not, and if it is ! than we will remove the lazy-img class (the blur effect) from that image and we will tell the observer API to stop observing that image. here's the code :

const imgTargets = ...

const loadImg = function (entries, observer) {
  const [entry] = entries;

  // check if the observer API is intersecting the image
  if (!entry.isIntersecting) return;

  // Replace src with data-src
  entry.target.src = entry.target.dataset.src;

  entry.target.addEventListener('load', function () {
    entry.target.classList.remove('lazy-img');
  });
  // stop observing the target image
  observer.unobserve(entry.target);
};

const imgObserver = ...
Enter fullscreen mode Exit fullscreen mode

show sticky navigation before leaving the header by ..px : Intersection Observer API

Alright!! we reach the end of this tutorial ! i hope that you learned something valuable today with me !

if you have any question, put it in the comment section and i will be happy to answer you !

complete project

Top comments (0)