Lazy Loading JavaScript on Scroll

Lazy Loading JavaScript on Scroll
Code Snippet:Lazy-load images with scroll event handler
Author: luongvanphuc
Published: May 12, 2024
Last Updated: May 12, 2024
Downloads: 64
License: MIT
Edit Code online: View on CodePen
Read More

Lazy loading images can significantly enhance the performance of your website by loading images only when they are needed. This JavaScript code enables lazy loading of images and background images on scroll. It loads images near the viewport dynamically.

You can use this code on websites to improve loading times. One benefit is enhanced performance.

How to Create Lazy Loading Images on Scroll Using JavaScript

1. In your HTML file, ensure that all images you want to lazy load have the data-src attribute instead of the src attribute. For background images, use a div with a class of your choice and the data-src attribute.

<img src="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=753&q=80" width="753" height="500">
<img src="https://images.unsplash.com/photo-1519046904884-53103b34b206?w=753&q=80" width="753" height="500">
<img data-src="https://images.unsplash.com/photo-1495954484750-af469f2f9be5?w=753&q=80" width="753" height="500" lazy>
<img data-src="https://images.unsplash.com/photo-1587502536900-baf0c55a3f74?w=753&q=80" width="753" height="500" lazy>
<img data-src="https://images.unsplash.com/photo-1510414842594-a61c69b5ae57?w=753&q=80" width="753" height="500" lazy>
<img data-src="https://images.unsplash.com/photo-1471922694854-ff1b63b20054?w=753&q=80" width="753" height="500" lazy>
<div data-src="https://images.unsplash.com/photo-1473186578172-c141e6798cf4?w=753&q=80" class="lazy-bg" lazy></div>
<div data-src="https://images.unsplash.com/photo-1487349384428-12b47aca925e?w=753&q=80" class="lazy-bg" lazy></div>
<div data-src="https://images.unsplash.com/photo-1527437934671-61474b530017?w=753&q=80" class="lazy-bg" lazy></div>
<div data-src="https://images.unsplash.com/photo-1473496169904-658ba7c44d8a?w=753&q=80" class="lazy-bg" lazy></div>

2. Style your images and background images as per your design requirements. Ensure that they have appropriate dimensions and styles. You can add classes and styles as needed.

img {
  display: block;
  max-width: 100%;
  margin: 10px auto;
  border: 0;
}

.lazy-bg {
  width: 753px;
  height: 500px;
  margin: 10px auto;
  background-size: cover;
  background-position: center;
}

3. Copy and paste the following JavaScript code into your project. This script detects when images are near the viewport and loads them dynamically.

Make sure to integrate the JavaScript file into your HTML file using a <script> tag. Place this script at the end of the <body> tag to ensure it doesn’t block other content from loading.

// duyệt tất cả tấm ảnh cần lazy-load
var lazyImages = document.querySelectorAll('[lazy]');

// khi tấm ảnh gần chạm viewport (còn 100px nữa là chạm), thì load tấm ảnh ngay
var threshold = 100;

// tránh vấn đề về performance
var timeout;

function lazyload () {
  clearTimeout(timeout);

  timeout = setTimeout(function() {
    var scrollTop = window.pageYOffset;
    lazyImages.forEach(function(lazyImage) {
      var src = lazyImage.dataset.src;

      // khi vị trí tấm ảnh gần chạm viewport, load ngay
      if (lazyImage.offsetTop < (window.innerHeight + scrollTop + threshold)) {
        lazyImage.tagName.toLowerCase() === 'img'
        // <img>: copy data-src sang src
          ? lazyImage.src = src

        // <div>: copy data-src sang background-image
        : lazyImage.style.backgroundImage = "url(\'" + src + "\')";

        // copy xong rồi thì bỏ attribute lazy đi
        lazyImage.removeAttribute('lazy');
      }
    });

    // tất cả tấm ảnh đã được load xong, dọn dẹp và đi thôi.
    if (lazyImages.length == 0) { 
      document.removeEventListener('scroll', lazyload);
    }
  }, 10);
}

document.addEventListener('scroll', lazyload);

You can customize the threshold value in the JavaScript code to adjust when images should start loading before they appear in the viewport. Additionally, you can modify the timeout value to control the delay between scroll events.

That’s all! hopefully, you have successfully created Lazy Loading Javascript On Scroll. If you have any questions or suggestions, feel free to comment below.

Leave a Comment