Simple Method To Lazy Load WooCommerce Product Images Without Plugin

Mostly users don’t like to visit website with slow speed. So its important if you are managing a website then it need to be fast loading speed. There are many factors that help to speed up a website. But today we are going to cover up WooCommerce Product images related speed up method and will let you know how to Lazy Load WooCommerce product images without the help of plugin. As we know there are number of plugins that we can use to lazy load WooCommerce product images but in that case there are number of JavaScript files and stylesheet files will load on the page and it will increase the number of page load requests.

So if we can do it without that request count then I will prefer to use our custom code to lazy load WooCommerce product images. I hope you will enjoy this post and will really help to increase you website speed and also will help in Google PageSpeed Insight score.

Images play important role for each website. It give a new look and  feel to a web page. Images are much bigger in size than text so when we use number of images in a article to describe content perfectly then it increase the size of page. So to fix this problem in WooCommerce there is a method that we can use for our website. We call it Lazy Load Method.

What Is Lazy Loading ?

Lazy Loading is a method to identify resources as non-blocking and load these resources only when needed. So it help to reduced the page loading time and will help to eliminate render-blocking resources. We are talking about WooCommerce images Lazy Loading so when we implement this method on images then it will only load the images that are on your computer screen. Lets suppose there are twelve products on a page and when we will open that page on browser then only the product images will load that part of page is displaying on your screen. When you will scroll to the bottom then the other product images will load.

How to Implement Lazy Load WooCommerce Product Images?

Lazy Load Woocommerce Product Images

There are different methods to implement Lazy loading for your WooCommerce website. There are number of plugins that help to implement Lazy Loading for WooCommerce. Now days  many themes comes with built in lazy loading feature. But today we are going to implement lazy loading without the help of plugins.

We will use our custom code to implement Lazy Loading. It will help to speed up your website and it is really easy to implement for your website. There are some simple steps to implement it for your website.

Step 1

Create a javascript file (lazyload.js) in your theme folder and add the scroll listener functionality in that file. Copy the scroll listener code below and paste in your created javascript file.


// Lazy load Woocommerce images
document.addEventListener("DOMContentLoaded", function() {
  let lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
  let active = false;

  const lazyLoad = function() {
    if (active === false) {
      active = true;

      setTimeout(function() {
        lazyImages.forEach(function(lazyImage) {
          if ((lazyImage.getBoundingClientRect().top <= window.innerHeight && lazyImage.getBoundingClientRect().bottom >= 0) && getComputedStyle(lazyImage).display !== "none") {
            lazyImage.src = lazyImage.dataset.src;
            lazyImage.srcset = lazyImage.dataset.srcset;
            lazyImage.classList.remove("lazy");

            lazyImages = lazyImages.filter(function(image) {
              return image !== lazyImage;
            });

            if (lazyImages.length === 0) {
              document.removeEventListener("scroll", lazyLoad);
              window.removeEventListener("resize", lazyLoad);
              window.removeEventListener("orientationchange", lazyLoad);
            }
          }
        });

        active = false;
      }, 200);
    }
  };

  lazyLoad();
  
  document.addEventListener("scroll", lazyLoad);
  window.addEventListener("resize", lazyLoad);
  window.addEventListener("orientationchange", lazyLoad);
});

Step 2

Open your theme folder function.php file and scroll to the end of file. Copy the code below and paste it at the end of your theme function.php


add_action('init', function(){
    remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
    add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
});

if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) {
    function woocommerce_template_loop_product_thumbnail() {
        echo woocommerce_get_product_thumbnail();
    } 
}

if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) {   
    function woocommerce_get_product_thumbnail( $size = 'shop_catalog' ) {
        global $post, $woocommerce;
        $output = '';

        if ( has_post_thumbnail() ) {
            $src = get_the_post_thumbnail_url( $post->ID, $size );
            $output .= '<img class="lazy" src="image" data-src="' . $src . '" data-srcset="' . $src . '" alt="" width="350" height="350">';
        } else {
             $output .= wc_placeholder_img( $size );
        }

        return $output;
    }
}

Now the last step is to enqueue the script file


add_action( 'wp_enqueue_scripts', 'woo_lazyloading_script' );
function woo_lazyloading_script() {
   
    wp_register_script( 'woo-lazyload', plugins_url( '/js/lazyload.js' , __FILE__ ) );

   
    wp_enqueue_script( 'woo-lazyload' );
}