text
stringlengths 1
80.5k
⌀ |
---|
Lazy Loading Images With The IntersectionObserver API In Angular 5.0.0 |
The other day, I was listening to a podcast about Flexbox with Rachel Andrew and Jen Simmons in which one of them (I can't remember which one) mentioned something called the IntersectionObserver API. From what they described, the IntersectionObserver API sounded like something that would be perfect for high-performance lazy-loading of images. In the past, I've looked at lazy-loading images in Angular.js 1.x; and, it's a complicated choreography of scroll actions, timers, life-cycle hooks, and the |
calculation of many bounding boxes. Which is exactly what the IntersectionObserver API is designed to encapsulate! As such, I wanted to see how we might be able to make the IntersectionObserver API available through a set of Angular 5 directives and services. |
Run this demo in my JavaScript Demos project on GitHub. |
The goal of the IntersectionObserver API is to track the visibility of a set of targets in relation to a given viewport. The viewport may be the browser's viewport; or, it may be an arbitrary element in the DOM that contains the target elements. As consumers of the API, we define the observer root, the target elements, and provide a callback. The IntersectionObserver then invokes our callback whenever the visibility of some subset of the target elements changes. |
It's easy to see that 90% of the lazy-loading-images task is being lifted off of our shoulders by the IntersectionObserver API. The last 10% of lazy-loading images requires us to tell the observer when to start and stop watching a given target; and, how to update the IMG src property when said target becomes visible. To do this, I'm going to create a [lazySrc] attribute directive that will replace the IMG element's native src attribute. This directive will then register itself with an |
IntersectionObserver-based abstraction that will turn around and call the directive when the associated element has become visible: |
// Import the core angular services. |
import { Directive } from "@angular/core"; |
import { ElementRef } from "@angular/core"; |
import { OnDestroy } from "@angular/core"; |
import { OnInit } from "@angular/core"; |
import { Renderer2 } from "@angular/core"; |
// Import the application components and services. |
import { LazyTarget } from "./lazy-viewport.ts"; |
import { LazyViewport } from "./lazy-viewport.ts"; |
// ----------------------------------------------------------------------------------- // |
// ----------------------------------------------------------------------------------- // |
@Directive({ |
selector: "[lazySrc]", |
inputs: [ |
"src: lazySrc", |
"visibleClass: lazySrcVisible" |
] |
}) |
export class LazySrcDirective implements OnInit, OnDestroy, LazyTarget { |
public element: Element; |
public src: string; |
public visibleClass: string; |
private lazyViewport: LazyViewport; |
private renderer: Renderer2; |
// I initialize the lazy-src directive. |
constructor( |
elementRef: ElementRef, |
lazyViewport: LazyViewport, |
renderer: Renderer2 |
) { |
this.element = elementRef.nativeElement; |
this.lazyViewport = lazyViewport; |
this.renderer = renderer; |
this.src = ""; |
this.visibleClass = ""; |
} |
// --- |
// PUBLIC METHODS. |
// --- |
// I get called once when the directive is being destroyed. |
public ngOnDestroy() : void { |
// If we haven't detached from the LazyViewport, do so now. |
( this.lazyViewport ) && this.lazyViewport.removeTarget( this ); |
} |
// I get called once after the inputs have been bound for the first time. |
public ngOnInit() : void { |
// Attached this directive the LazyViewport so that we can be alerted to changes |
// in this element's visibility on the page. |
this.lazyViewport.addTarget( this ); |
} |
// I get called by the LazyViewport service when the element associated with this |
// directive has its visibility changed. |
public updateVisibility( isVisible: boolean, ratio: number ) : void { |
// When this target starts being tracked by the viewport, the initial visibility |
// will be reported, even if it is not visible. As such, let's ignore the first |
// visibility update. |
if ( ! isVisible ) { |
return; |
} |
// Now that the element is visible, load the underlying SRC value. And, since we |
// no longer need to worry about loading, we can detach from the LazyViewport. |
this.lazyViewport.removeTarget( this ); |
this.lazyViewport = null; |
this.renderer.setProperty( this.element, "src", this.src ); |
// If an active class has been provided, add it to the element. |
( this.visibleClass ) && this.renderer.addClass( this.element, this.visibleClass ); |
} |
} |
A lot of this directive is boiler-plate(ish). But, if you look at the ngOnInit() life-cycle hook, you can see that this directive is registering itself with an injected instance of the LazyViewport service: |
this.lazyViewport.addTarget( this ); |
The LazyViewport service requires that the registered directive implement the LazyTarget interface, which exposes the the Element to target and an updateVisibility() callback method. The LazyViewport service then configures the IntersectionObserver - if it's supported by the browser - registeres its own callback and, when the callback is invoked, turns around and invokes the updateVisibility() method associated with the targeted element's directive instance. |
export interface LazyTarget { |
element: Element; |
updateVisibility: ( isVisible: boolean, ratio: number ) => void; |
} |
export class LazyViewport { |
private observer: IntersectionObserver; |
private targets: Map<Element, LazyTarget>; |
// I initialize the lazy-viewport service. |
constructor() { |
this.observer = null; |
// The IntersectionObserver watches Elements. However, when an element visibility |
// changes, we have to alert an Angular Directive instance. As such, we're going |
// to keep a map of Elements-to-Directives. This way, when our observer callback |
// is invoked, we'll be able to extract the appropriate Directive from the |
// Element-based observer entries collection. |
this.targets = new Map(); |
} |
// --- |
// PUBLIC METHODS. |
// --- |
// I add the given LazyTarget implementation to the collection of objects being |
// tracked by the IntersectionObserver. |