Skip to content

Instantly share code, notes, and snippets.

@yakuzaaaa
Last active February 21, 2019 11:25
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 yakuzaaaa/1a0c46bc20f97aabbfede7d99f44dc81 to your computer and use it in GitHub Desktop.
Save yakuzaaaa/1a0c46bc20f97aabbfede7d99f44dc81 to your computer and use it in GitHub Desktop.
import { Directive, ElementRef, Input, OnChanges, SimpleChanges } from '@angular/core';
@Directive({
selector: '[lazy-load]' // Attribute selector
})
export class LazyLoadDirective implements OnChanges {
@Input('source')
source;
lazyImageObserver: any;
constructor(private el: ElementRef) {}
ngOnChanges(changes: SimpleChanges) {
if (changes.source) {
this.observeAndLazyLoadImages(this.el.nativeElement);
}
}
private observeAndLazyLoadImages(lazyImage: Element) {
const intersectionObsPresent = "IntersectionObserver" in window;
if (intersectionObsPresent) {
if (this.lazyImageObserver) {
this.lazyImageObserver.unobserve(lazyImage);
this.lazyImageObserver = null;
}
this.lazyImageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
this.setImageSrcFromDataset(entry.target);
this.lazyImageObserver.unobserve(entry.target);
this.lazyImageObserver = null;
}
});
});
this.lazyImageObserver.observe(lazyImage);
} else {
// Since IntersectionObserver is not supported by the browser
// we will load all images right away
this.setImageSrcFromDataset(lazyImage);
}
}
private setImageSrcFromDataset(imageTag) {
imageTag.src = this.source;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment