Setting LazyLoad Images in WordPress without a Plugin

lazy loading images in wordpress
Table of Content

Rey.web.idLazyload is a way to prevent images from loading before we scroll past them. There are many plugins that help you with this, some themes even have built-in lazy loading functionality.

One way to speed up website loading is by implementing Lazyload. What is Lazyload? Images are very important content on a website. The better the image quality, the larger the size. This makes the page size bigger, so the page load takes a long time. To overcome this, use Lazyload.

Lazyload is the most important part of a website. Like it or not, if you want your website to load faster, you have to implement Lazyload. But how to implement it?

What is Lazyload?

Lazyload is a technique for making the loading of images on a website asynchronous, meaning that once the top content is completely loaded, the images will not load.

This can be said if the user does not scroll completely, then the image placed at the bottom of the page will not load. So, the browser will not load the image if the user does not scroll to the image.

Lazyload works by loading images only if the user has scrolled to the location where the image will be visible in the viewport, Otherwise, the images will never be loaded.

Why You Should Use Lazyload

Lazyload gives you many benefits, therefore you should start considering implementing Lazyload on your website. So, here are several reasons why you should use Lazyload on your website.

  • Because images are only loaded when they are visible in the viewport, the website will choose to load faster. Apart from that, by implementing lazy load, you can save more bandwidth and server resources.
  • Because Lazyload makes image loading asynchronous, it can make the difference between users staying or leaving a website.
  • If your website uses JavaScript to display content or provide some kind of functionality to users, loading the DOM quickly is very important. Most scripts wait until DOM loading is complete before starting to run. With Lazyload, this makes loading faster.
  • Improving User Experience, By implementing Lazyload on the website you can indirectly improve user experience. For users who access the website on a mobile device and have a slow connection, Lazyload is very helpful.

Here we will show you that implementing it yourself is not difficult. add the code on functions.php
Step 1: Replace SRC Attribute

add_filter( 'the_content', 'my_lazyload_content_images' );
add_filter( 'widget_text', 'my_lazyload_content_images' );
add_filter( 'wp_get_attachment_image_attributes', 'my_lazyload_attachments', 10, 2 );

// Replace the image attributes in Post/Page Content
function my_lazyload_content_images( $content ) {
  $content = preg_replace( '/(<img.+)(src)/Ui', '$1data-$2', $content );
  $content = preg_replace( '/(<img.+)(srcset)/Ui', '$1data-$2', $content );
  return $content;
}

// Replace the image attributes in Post Listing, Related Posts, etc.
function my_lazyload_attachments( $atts, $attachment ) {

  if(!is_admin()){
  $atts['data-src'] = $atts['src'];
  unset( $atts['src'] );
  
  if( isset( $atts['srcset'] ) ) {
    $atts['data-srcset'] = $atts['srcset'];
    unset( $atts['srcset'] );
  }
  }

  return $atts;
}

function lazy_image_css_js() { 
?>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>
<script id="rendered-js" >
( function() { 'use strict';
  let images = document.querySelectorAll('img[data-src]');
              
  document.addEventListener('DOMContentLoaded', onReady);
  function onReady() {
    // Show above-the-fold images first
    showImagesOnView();

    // scroll listener
    window.addEventListener( 'scroll', showImagesOnView, false );
  }
  
  // Show the image if reached on viewport
  function showImagesOnView( e ) {
    
    for( let i of images ) {
      if( i.getAttribute('src') ) { continue; } // SKIP if already displayed
      
      // Compare the position of image and scroll
      let bounding = i.getBoundingClientRect();
      let isOnView = bounding.top >= 0 &&
      bounding.left >= 0 &&
      bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      bounding.right <= (window.innerWidth || document.documentElement.clientWidth);
      
      if( isOnView ) {
        i.setAttribute( 'src', i.dataset.src );
        if( i.getAttribute('data-srcset') ) {
          i.setAttribute( 'srcset', i.dataset.srcset );
        }
      }
    }
  }
              
})();
</script>
<style>
img[data-src] {
  opacity: 0;
  transition: opacity .25s ease-in-out;
  will-change: opacity;
}

/* appear animation */
img[data-src][src] {
  opacity: 1;
}
</style>
<?php } 
add_action('wp_footer', 'lazy_image_css_js');

Conclusion

Lazyload has become a necessity on all blogs and company websites. Regarding SEO, you don’t need to worry because Google itself has confirmed that they can detect lag.

There’s no harm in using a plugin for this feature, but it’s good to know how to do it. You can also customize it to your needs such as adjusting animations and adding delays.