Category
Software Engineering

Published
Jan 25, 2016

Read
4 min

Tweet
Share
Comment

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.

I used the commonly understood "lazy load" term in the article title though I think "smart load" or "JIT load" is more fitting. As a result, I use "smart-src" for the directive implementation.

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
  1. create the attribute directive smartSrc
  2. set its isolate scope properties: smartSrc and smartSrcWatch
  3. $watch scope.smartSrcWatch in the directive's link function
  4. add the src attribute to the element when the $watch validates
  5. cleanup the $watch
HTML
  1. add the smart-src attribute to the <img> in replace of src
  2. add the smart-src-watch attribute to the <img> with its value set to slide.active
This approach is abstract enough to be useful with other components where 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.