Lazy Carousel in Bootstrap

Easy-peasy way to lazy load images in a bootstrap carrousel:

  1. Use data-src instead of src for all but the first image.
  2. Add lazy class to the carousel (optional, just to have an opt-in class for lazy carousels).
  3. At the slide event, set the src attribute on the not-lazy-anymore image.

HTML code:

<div class="carousel slide lazy">
  <div class="carousel-inner" role="listbox">
    <div class="item active">
      <img src="first-image.jpg" alt="First image">
    </div>
    <div class="item">
      <img data-src="second-image.jpg" alt="Second image">
    </div>
  </div>
</div>

Javascript code:

$(function() {
  return $(".carousel.lazy").on("slide", function(ev) {
    var lazy;
    lazy = $(ev.relatedTarget).find("img[data-src]");
    lazy.attr("src", lazy.data('src'));
    lazy.removeAttr("data-src");
  });
});