Blog

Lazy load images in a Bootstrap carousel


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)

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 decrease in height

  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');

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

           $this.attr('src', src)

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

        }

    });

});