Last active
September 8, 2020 12:32
-
-
Save realtomaszkula/95b042c7e2a349ea79a83c66441ec658 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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