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('', function(e) {

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

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

  // prevents the slide decrease in height

  if (cHeight == 0) {

    cHeight = $(this).height();



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


        var $this = $(this),

            src = $'src');

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

           $this.attr('src', src)

           $'src', '');