Lazy Load Images in Bootstrap Carousel for Faster Page Loads

File Size: 9.13 KB
Views Total: 229
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Lazy Load Images in Bootstrap Carousel for Faster Page Loads

lazy-load-bootstrap-carousel is a jQuery plugin for Bootstrap 5 that delays the loading of images within your Bootstrap carousel component.

It fetches images only when their corresponding slide becomes active. This directly improves initial page load time, a critical factor for user experience and Core Web Vitals.

Use cases:

  • Hero Carousels: Many sites feature a large, full-width carousel at the top of the page. Loading all of those high-resolution images at once can severely impact the Largest Contentful Paint (LCP) score. This plugin makes sure only the first visible image loads initially.
  • Product Galleries: A product detail page might have a carousel with numerous images. A user may only view the first few. Deferring the rest saves significant bandwidth for both the user and your server.
  • Project Showcases: When a carousel is used to display a gallery of projects, loading all the media upfront is inefficient. This plugin can be useful for making portfolio sites feel much snappier on first visit.

How to use it:

1. Include the required dependencies in your HTML document. The plugin requires jQuery and Bootstrap 5 framework:

<link rel="stylesheet" href="/path/to/cdn/bootstrap.min.css" />
<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/cdn/bootstrap.bundle.min.js"></script>

2. Download and load the lazy-load-bootstrap-carousel plugin's script after jQuery.

<script src="js/lazy-bootstrap-carousel-v5.js"></script>

3. In your carousel's HTML, the first .carousel-item should be standard. Its <img> tag uses the normal src attribute. This is the image that loads with the page. For all subsequent carousel items, change the src attribute on the <img> tag to lazy-src. The plugin will use this attribute to find the image path when it's time to load it.

<div id="main-carousel" class="carousel slide">
  <!-- Carousel Indicators -->
  <div class="carousel-indicators">
    <button type="button" data-bs-target="#main-carousel" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
    <button type="button" data-bs-target="#main-carousel" data-bs-slide-to="1" aria-label="Slide 2"></button>
    <button type="button" data-bs-target="#main-carousel" data-bs-slide-to="2" aria-label="Slide 3"></button>
  </div>
  <!-- Add Images Here -->
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="1.jpg" class="d-block w-100" alt="Jaipur" title="Slide 1">
      <div class="carousel-caption d-none d-md-block">
        <h3>Slide 1</h3>
        <p>Slide 1 Content</p>
      </div>
    </div>
    <div class="carousel-item">
      <img lazy-src="2.jpg" class="d-block w-100" alt="Jaipur" title="Slide 2">
      <div class="carousel-caption d-none d-md-block">
        <h3>Slide 2</h3>
        <p>Slide 2 Content</p>
      </div>
    </div>
    <div class="carousel-item">
      <img lazy-src="3.jpg" class="d-block w-100" alt="Jaipur" title="Slide 2">
      <div class="carousel-caption d-none d-md-block">
        <h3>Slide 3</h3>
        <p>Slide 3 Content</p>
      </div>
    </div>
  </div>
  <!-- Loading Indicator -->
  <div class="loading d-none">
    <img src="img/black.png" alt="loading">
  </div>
  <!-- Navigation Buttons -->
  <button class="carousel-control-prev" type="button" data-bs-target="#main-carousel" data-bs-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
  </button>
  <button class="carousel-control-next" type="button" data-bs-target="#main-carousel" data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
  </button>
</div>

4. Initialize the carousel and activate lazy loading functionality:

$(function(){
  var element = document.getElementById('main-carousel');
  if(element){
    var carousel = new bootstrap.Carousel(element,{interval:3000, ride:true});
    $(element).lazyCarousel();
  }
});

How It Works

The plugin works by intercepting Bootstrap's carousel slide events and managing image loading states. When initialized, it attaches an event listener to the carousel's slide.bs.carousel event, which fires before each slide transition begins.

During slide transitions, the plugin checks if the target slide contains an image with the lazy-src attribute. If found, it prevents the default carousel transition, displays the loading indicator, and begins loading the image by copying the lazy-src value to the src attribute.

Once the image loads successfully or encounters an error, the plugin removes the lazy-src attribute, hides the loading indicator, and programmatically triggers the carousel transition to the intended slide using Bootstrap's carousel API.

Alternatives

  • Native loading="lazy": Modern browsers support native image lazy loading. You can add loading="lazy" to your <img> tags. This is a great, JS-free solution for images below the fold. For carousels, however, its behavior can be unpredictable. The browser decides when to load the image, which might be too late for a smooth slide transition, causing a blank space to appear momentarily. This plugin offers more precise control for a better in-carousel experience.
  • Intersection Observer API: You could build this functionality yourself using the Intersection Observer API. This is a more modern and powerful approach that doesn't require jQuery. It is also more work. This plugin is a quick, effective solution if you are already in a jQuery and Bootstrap ecosystem.

FAQs

Q: What happens if an image fails to load?
A: The script listens for both load and error events on the image. If an image fails to load, the plugin will still hide the loading indicator and complete the slide transition. The user will see the browser's broken image icon, but the carousel itself will not get stuck.

Q: Does this plugin work with responsive images or srcset attributes?
A: The plugin works with standard src attributes only. For responsive images, you would need to modify the plugin to handle srcset attributes or implement additional logic to manage different image sizes based on viewport.

Q: Can I customize the loading indicator appearance?
A: Yes, the loading indicator uses the .loading class within your carousel. You can style this element with custom CSS or replace the loading image with your preferred spinner or animation.

Learn More About Lazy Loading


This awesome jQuery plugin is developed by mconventi. For more Advanced Usages, please check the demo page or visit the official website.