Lazy Loading images in Vanilla JavaScript: Improving Website Performance
Tags: lazyload, javascript, beginners, firstpost
Published: 2023-02-22 03:51:21

## Introduction
Web performance is critical to the success of any website, and lazy loading is a technique that can help improve it. Lazy loading is the process of loading only the necessary resources or elements of a web page when the user needs them, instead of loading everything upfront. This technique can significantly reduce page load times, improve the user experience, and reduce server load. In this article, we will explore how to implement lazy loading in vanilla JavaScript.

Images are frequently used in any website, but they can also significantly affect how quickly a page loads at first. When there are numerous images on a page, the total file size can increase significantly because images are frequently huge files that take time to download. Hence, before rendering a page when a user accesses a website, the browser must download every image on the page, which might delay the site's initial loading time. Web developers can use lazy loading or other optimization strategies to postpone the loading of non-critical pictures or to load images just as they are needed and are displayed on the screen to solve this problem.

## What is Lazy Loading?
Lazy loading is a technique that defers the loading of non-critical resources or elements of a web page until the user needs them. This can include images, videos, and other media, as well as JavaScript and CSS files. By delaying the loading of these resources, the initial page load time can be significantly reduced, resulting in faster page rendering and better user experience.

## How does Lazy Loading Work?
The lazy loading process typically involves detecting when a resource or element is in the viewport or near it and then triggering its loading. In JavaScript, this can be accomplished using a combination of event listeners, Intersection Observer API, and lazy loading libraries.

## Using "loading='lazy'" 
The attribute tells the browser to only load an image when it enters the viewport, instead of loading it immediately when the page is opened. This can help reduce the initial page load time and improve the user experience, especially on websites with many large images.

```
<img src="src/images/test/png" alt="test" loading="lazy"/>
```
## Using Intersection Observer API
We can use Intersection Observer API to implement lazy loading in vanilla javascript. It is widely supported across 95% of the browsers. Here's how we can implement

```
<img data-src="src/images/test/png" alt="test" class="lazy"/>
<script>

function lazyload() {
 const lazyLoadImages = document.querySelectorAll(".lazy");

const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const lazyImage = entry.target;
            lazyImage.src = lazyImage.dataset.src;
            lazyImage.classList.remove("lazy");
            imageObserver.unobserve(lazyImage);
          }
        });
      });

lazyLoadImages.forEach((lazyImage) => {
        imageObserver.observe(lazyImage);
      });
}

document.addEventListener("DOMContentLoaded", lazyload);
</script>
```

In this example, we first select all images that have a ".lazy" class. We then create an IntersectionObserver object with a callback function that is called when an image is in the viewport. The callback function checks whether the image is intersecting with the viewport and, if so, replaces the src attribute with the value of data-src, which is the actual image source. Finally, we remove the lazy class from the image and stop observing it.

## Conclusion
Lazy loading is a powerful technique that can significantly improve web performance and user experience. By deferring the loading of non-critical resources or elements, we can reduce initial page load times and decrease server load. In this article, we explored how to implement lazy loading in vanilla JavaScript using the Intersection Observer API. With lazy loading, we can create faster and more responsive web pages that keep users engaged and satisfied. Keep in mind the performance pf website doesn't just depend on images, there are several other factors that also affect laoding time.