How to implement a lazy loading mechanism for images with jQuery



Image not found!!


Lazy loading is a technique used to defer the loading of images on a web page until they are actually needed. This can help improve page loading performance, especially on pages with a large number of images. jQuery provides a simple way to implement lazy loading. Here's a basic example:

  1. Include jQuery: Make sure to include jQuery in your HTML file. You can use a CDN or download and host the library locally.
html
<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  1. Add a data-src attribute: Replace the src attribute of your images with a data-src attribute. This attribute will store the actual image URL.
html
<img data-src="path/to/your/image.jpg" alt="Your Image">
  1. Implement lazy loading with jQuery: Use jQuery to handle the lazy loading behavior. You can do this by checking if the images are in the viewport when the page loads or when the user scrolls.
html
<script> $(document).ready(function () { // Function to check if an element is in the viewport function isElementInViewport(el) { var rect = el.getBoundingClientRect(); return ( rect.bottom >= 0 && rect.right >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth) ); } // Function to lazy load images function lazyLoadImages() { $('img[data-src]').each(function () { if (isElementInViewport(this)) { $(this).attr('src', $(this).data('src')).removeAttr('data-src'); } }); } // Initial load lazyLoadImages(); // Bind to the scroll event to lazy load images on scroll $(window).on('scroll', lazyLoadImages); }); </script>

This script checks if each image with the data-src attribute is in the viewport, and if so, it replaces the data-src attribute with the src attribute to trigger the actual image loading.

Note: Consider combining this approach with a debounce or throttle mechanism for the scroll event to avoid excessive calls to lazyLoadImages and improve performance. Additionally, you might want to customize and extend this code based on your specific requirements.