Lazy loading images using Intersection-Observer API - JavaScript
Published: 2021-08-07 11:27:01

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] (https://aykacode.com/2021/07/09/javascript-sticky-navigation-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
<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>

```

**Now lets make them more beautiful! **
```css
.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);
}
```
> [show a section on scroll + transition animation using the IntersectionObserver API] (https://aykacode.com/2021/07/09/javascript-show-a-section-on-scroll-transition-animation/)

**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) :
```javascript
// Lazy loading images
const imgTargets = document.querySelectorAll('img[data-src]');
```
next, we will let our intersectionObserver API observe every selected image :
```javascript
...
const imgObserver = new IntersectionObserver(loadImg, {
  root: null,
  threshold: 0,
  rootMargin: '200px',
});
// observer every selected image
imgTargets.forEach(img => imgObserver.observe(img));
```

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

[complete project] (https://codepen.io/kanipen/pen/vYmXyrJ)

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 :
```javascript
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 = ...
```

> [show sticky navigation before leaving the header by ..px : Intersection Observer API] (https://aykacode.com/2021/07/09/javascript-sticky-navigation-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] (https://codepen.io/kanipen/pen/vYmXyrJ)