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...
Easy-peasy way to lazy load images in a bootstrap carrousel: Use data-src instead of src for all but the first image. Add lazy class to the carousel (optional, just to have an opt-in class for lazy carousels). At the slide event, set the src attribute on the not-lazy-anymore image.
Approach 1: We can control the animation by using the data interval attribute of each carousel item. The given example is the best example for understanding this concept. The Data-interval attribute is used to set the interval time between two carousel item by default its value is 3000 milliseconds.
In browsers where the Page Visibility API is supported, the carousel will avoid sliding when the webpage is not visible to the user (such as when the browser tab is inactive, the browser window is minimized, etc.).
To turn off the autoplay set data-mdb-interval="false" next to a . carousel .
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With