I have got the bootstrap carousel working on my web page and i want it to lazy load. I have found this piece of code on the internet:
$("#myCarousel").bind("slid", function(){
$img = $(".active img", this);
$img.attr("src", $img.data('lazy-load-src'));
});
This causes the carousel to "load" the current image when the next button (or prev) button is clicked. I want it to load not the current image but the image after that, and the image in front of the current image, so that i still have the nice sliding animation. And not a loading image.
So my question is how do I set the lazy-load-src to src of the previous image and of the next image when the next button is clicked?
There are several options, depending on the precision you need, but you should keep the
lazy-load-src
to their ownimg
tags.You can use selectors, put in
data-
attributes and use that to select your next image to load. But this is messy.I think your best shot is using the
.next()
method on your items, so that onslid
you load the next image. Something like :I've updated Sherbrows answer a bit to support Bootstrap v3 and a random start index. I'm using a page of thumbnails. When a user clicks a thumb, the carousel should start at that index.
Show the carousel
Do lazy loading
I took Arnoud Sietsema's answer a step further. The images in your carousel could have loading gifs to begin with. Then...
Show the carousel
Do lazy loading
The difference is that, when trying to load the next slide, it's first loaded 'under the hood', and, only when loaded, inserted into the carousel. As a result, the loading image is shown until the image is fully loaded.
Also, the carousel can now be moved in both directions.