Lazy Loading Carousel Images in Angular Bootstrap
Article Purpose
The purpose of this article is to present an extemely simple and powerful attribute directive that allows for the Angular Bootstrap Carousel component to lazy load its images. In fact, I think this solution would work just as well for many other components. The Accordion, Collapse, Dropdown, and Tabs components specifically come to mind.
Though I haven't tested it, the solution should work with any element that takes a src
attribute. I'm looking at you <audio>
and <video>
.
Problem
A common issue with Carousel implementations is that they often times load all of their images when only a small subset are ever viewed. The Angular Bootstrap Carousel component is no exception. I think this functionality should be built into Angular Bootstrap because it is a waste of resources to load unneeded images (both from a server-side and client-side perspective). Thankfully, there is a simple solution.
Solution
In spending a little time brainstorming solutions, I was able to land on a light and clean approach. The approach is similar to the web's traditional "lazy loading" solution, but without the need to track each image's vertical position in the document in relation to the scroll position. In fact, my solution is independent of both vertical and horizontal positional tracking. The approach goes like this:
JavaScript
- create the attribute directive
smartSrc
- set its isolate scope properties:
smartSrc
andsmartSrcWatch
$watch
scope.smartSrcWatch
in the directive'slink
function- add the
src
attribute to theelement
when the$watch
validates - cleanup the
$watch
HTML
- add the
smart-src
attribute to the<img>
in replace ofsrc
- add the
smart-src-watch
attribute to the<img>
with its value set toslide.active
slide.active
can be replaced with a different $watch
trigger.Code
JavaScript
HTML
As you can see, both the JavaScript and the HTML are really straightforward. If you want to play with an example you can check out this codepen which I happened to fork from Fabiano (for a shareable Angular Carousel example jump off point). Simply open the dev tools network tab and/or console to confirm that the <img> src
loads when desired.
If you have improvement ideas or any other thoughts, just reach out on Twitter @derekknox or email me derek [at] derekknox.com.