Lazy carousel in bootstrap
Easy-peasy way to lazy load images in a bootstrap carrousel:
- Use
data-src
instead ofsrc
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 thesrc
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");
});
});
Related protips:
Written by rewritten2
Related protips
6 Responses
Add your response
Thank you for sharing.
I think in the current Bootstrap version http://getbootstrap.com/javascript/#carousel the slide function is called 'slide.bs.carousel'.
Now working for me :)
Your code is really interesting.
In my case, each item of the carousel have more than one image.
So, with this code, instead of having all my images, I just had the first that is repeated. So, if i have 10 images in one page of the carousel, all are the same.
Do you have a solution for that ?
Thanks :)
i found 2 solutions :
First, you have to put this code just before :
jQuery.fn.extend({
renameAttr: function( name, newName, removeData ) {
var val;
return this.each(function() {
val = jQuery.attr( this, name );
jQuery.attr( this, newName, val );
jQuery.removeAttr( this, name );
// remove original data
if (removeData !== false){
jQuery.removeData( this, name.replace('data-','') );
}
});
}
});
- if you want to load picture with the carousel you add this after :
$(function() {
return $(".carousel").on("slide.bs.carousel", function(ev) {
$(this).find('.loadClick').renameAttr('data-src', 'src' );
});
- if you want to load picture with the modal you add this after :
$(function() {
$('.modal').on("shown.bs.modal", function (e) {
$(this).find('img').renameAttr('data-src', 'src' );
});
});
It works really well after changing the slide function as suggested in one of the comments. However, I noticed one problem. As the carousel goes to the second or subsequent images, the carousel collapses (to zero height) while the image is being downloaded and then expands back again. This creates a very bad and jarring effect. I found a solution to this here: https://coderwall.com/p/uf2pka/normalize-twitter-bootstrap-carousel-slide-heights