Lazy Load Images in WordPress

Lazy Load Images in WordPress

The lazy Loading in word press can be achieved by adding following java script code

document.addEventListener('DOMContentLoaded', function() {
 var images = document.querySelectorAll('img[data-src]');
 var imageObserver = new IntersectionObserver(function(entries, observer) {
    entries.forEach(function(entry) {
      if (entry.isIntersecting) {
        var image = entry.target;
        image.src = image.dataset.src;
        image.onload = function() {
          image.classList.remove('lazy-load');
        }
        observer.unobserve(image);
      }
    });
 });
 images.forEach(function(image) {
    imageObserver.observe(image);
 });
});

Later on you can enqueue this JS using word press hook in active themes functions.php

wp_enqueue_script('lazy-load-images', get_stylesheet_directory_uri() . '/js/lazy-load-images.js', array(), '1.0.0', true);

Leave a Reply

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