Skip to content

Instantly share code, notes, and snippets.

@davidmarquis
Last active April 11, 2017 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidmarquis/a702508f86679aa5a7b899a3499fbd15 to your computer and use it in GitHub Desktop.
Save davidmarquis/a702508f86679aa5a7b899a3499fbd15 to your computer and use it in GitHub Desktop.
Angular 2: Lazy-loading images using bLazy.js
import { Directive, ElementRef, Input, AfterViewChecked, OnDestroy } from "@angular/core";
import * as Blazy from "blazy";
/**
* Directive to setup lazy image loading using bLazy.
* Apply the directive on a container element that is a parent of `img` elements configured for bLazy.
* The container element must have an ID and be scrollable (overflow: scroll).
*
* Sample usage:
*
* <div id="blazyContainer" [bLazyLoadImages]="someVariableThatChanges" [bLazyOffset]="300" style="overflow: scroll;">
* <div *ngFor="let image of images">
* <img class="b-lazy" src="placeholder.jpg" [attr.data-src]="image" />
* </div>
* </div>
*
*/
@Directive({
selector: '[bLazyLoadImages]',
})
export class BlazyDirective {
@Input() bLazyOffset: number = 200;
bLazyInstance: any = null;
constructor(private elementRef: ElementRef) {}
ngOnDestroy() {
this.destroyBlazy();
}
@Input() set bLazyLoadImages(value: any) {
// deferred execution allows bLazy to properly initialize and bind itself.
setTimeout(() => {
this.destroyBlazy();
this.setupBlazy();
}, 100);
}
private setupBlazy() {
if (this.bLazyInstance) {
return;
}
let elementId = this.elementRef.nativeElement.id;
if (!elementId) {
throw Error("The element onto which the [bLazyLoadImages] directive is applied must have an id.");
}
this.bLazyInstance = new Blazy({
container: '#' + elementId,
root: this.elementRef.nativeElement,
offset: this.bLazyOffset,
});
}
private destroyBlazy() {
if (this.bLazyInstance) {
this.bLazyInstance.destroy();
this.bLazyInstance = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment