Skip to content

Instantly share code, notes, and snippets.

@realtomaszkula
Last active September 8, 2020 12:32
Show Gist options
  • Save realtomaszkula/95b042c7e2a349ea79a83c66441ec658 to your computer and use it in GitHub Desktop.
Save realtomaszkula/95b042c7e2a349ea79a83c66441ec658 to your computer and use it in GitHub Desktop.
import { AfterViewInit, Directive, ElementRef, HostBinding, Input } from '@angular/core';
@Directive({
selector: 'img[appLazyLoad]'
})
export class LazyLoadDirective implements AfterViewInit {
@HostBinding('attr.src') srcAttr = null;
@Input() src: string;
constructor(private el: ElementRef) {}
ngAfterViewInit() {
this.canLazyLoad() ? this.lazyLoadImage() : this.loadImage();
}
private canLazyLoad() {
return window && 'IntersectionObserver' in window;
}
private lazyLoadImage() {
const obs = new IntersectionObserver(entries => {
entries.forEach(({ isIntersecting }) => {
if (isIntersecting) {
this.loadImage();
obs.unobserve(this.el.nativeElement);
}
});
});
obs.observe(this.el.nativeElement);
}
private loadImage() {
this.srcAttr = this.src;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment