Bootstrap Carousel Lazy Load

RubyNoob picture RubyNoob · Oct 2, 2012 · Viewed 21.3k times · Source

I'm trying to have the bootstrap Carousel lazy load. It seems like this should be straight forward, but I'm not even getting any errors here to troubleshoot. JS:

<script type="text/javascript">
    $('#bigCarousel').on("slid", function() {
        // load the next image after the current one slid
        var $nextImage = $('.active.item', this).next('.item').find('img');
        $nextImage.attr('src', $nextImage.data('lazy-load-src'));
    });

</script>

And then html:

<div id="bigCarousel" class="carousel slide">
  <div class="carousel-inner">
    <div class="active item">
        <img src="assets/bigimage1.jpg" class="img-big">
    </div>
    <div class="item">
        <img data-lazy-load-src="assets/menu-header2.jpg" class="img-big">
    </div>
 </div>
</div>

No JS errors in firebug or anything else I can figure out, but my images just aren't loading. Probably something stupidly simple here...

Answer

ymakux picture ymakux · Jan 26, 2016

The simplest solution would be:

<div id="carousel" class="carousel slide lazy-load" data-ride="carousel" data-interval="false">
<div class="carousel-inner">
  <div class="item active"><img src="image1.jpg"></div>
  <div class="item"><img data-src="image2.jpg"></div>
  <div class="item"><img data-src="image3.jpg"></div>
</div>
<!-- controls -->
<ol class="carousel-indicators">
    <li data-target="#carousel" data-slide-to="0" class="active"></li>
    <li data-target="#carousel" data-slide-to="1"></li>
    <li data-target="#carousel" data-slide-to="2"></li>
  </ol>
</div>

<script>
$(function() {
    $('.carousel.lazy-load').bind('slide.bs.carousel', function (e) {
        var image = $(e.relatedTarget).find('img[data-src]');
        image.attr('src', image.data('src'));
        image.removeAttr('data-src');
    });
});
</script>

That's it!