2020
March (1)
Creating a new .NET Core project with authorisation
2019
April (1)
Getting started with GIT and Visual Studio
2018
July (1)
Lazy load images in a Bootstrap carousel
2017
September (1)
July (1)
07 July 2018
No need for this any more - modern browsers (except Safari) will accept
loading=lazy
in the img tag, so you don't need to do this.
We make a lot of use of the Bootstrap carousel, but when we run a Lighthouse audit we get the recommendation to lazy-load offscreen images.
We can do that by changing the img tag of the non-active items to (for example)
img alt="Slide 3" class="portrait" data-src="upload/slide_3_p.jpg"
We can then load the images as required like this:
var cHeight = 0; $('#carousel-custom').on('slide.bs.carousel', function(e) { var $nextImage = $(e.relatedTarget).find('img'); $activeItem = $('.active.item', this); // prevents the slide decreasing in height before the image is loaded if (cHeight == 0) { cHeight = $(this).height(); $activeItem.next('.item').height(cHeight); } // you might have more than one image per carousel item $nextImage.each(function(){ var $this = $(this), src = $this.data('src'); // skip if the image is already loaded if (typeof src !== "undefined" && src != "") { $this.attr('src', src) $this.data('src', ''); } }); });