Blog

Lazy load images in a Bootstrap carousel


No need for this any more - modern browsers (except Safari) will accept

loading=lazy

in the img tag, so you don't need to do this.

We make a lot of use of the Bootstrap carousel, but when we run a Lighthouse audit we get the recommendation to lazy-load offscreen images.

We can do that by changing the img tag of the non-active items to (for example)

img alt="Slide 3" class="portrait" data-src="upload/slide_3_p.jpg" 

We can then load the images as required like this:

var cHeight = 0;

$('#carousel-custom').on('slide.bs.carousel', function(e) {

  var $nextImage = $(e.relatedTarget).find('img');

  $activeItem = $('.active.item', this);

  // prevents the slide decreasing in height before the image is loaded

  if (cHeight == 0) {

    cHeight = $(this).height();

    $activeItem.next('.item').height(cHeight);

  }

// you might have more than one image per carousel item

$nextImage.each(function(){

        var $this = $(this),

            src = $this.data('src');

  // skip if the image is already loaded

        if (typeof src !== "undefined" && src != "") {

           $this.attr('src', src)

           $this.data('src', '');

        }

    });

});