-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathcloudinary-lazy-load.directive.ts
50 lines (43 loc) · 1.26 KB
/
cloudinary-lazy-load.directive.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import {AfterViewInit, Directive, ElementRef} from '@angular/core';
import { isBrowser } from './cloudinary.service';
@Directive({
selector: 'cl-image[loading=lazy]'
})
export class LazyLoadDirective implements AfterViewInit {
constructor(private el: ElementRef) {}
ngAfterViewInit() {
if (isBrowser()) {
if (!this.isNativeLazyLoadSupported() && this.isLazyLoadSupported()) {
this.lazyLoad();
} else {
this.loadImage();
}
}
}
loadImage() {
const nativeElement = this.el.nativeElement;
const image = nativeElement.children[0];
image.setAttribute('src', image.dataset.src);
}
isLazyLoadSupported() {
return window && 'IntersectionObserver' in window;
}
isNativeLazyLoadSupported() {
return 'loading' in HTMLImageElement.prototype; // check loading property is defined on image or iframe
}
lazyLoad() {
const options = {
rootMargin: `0px 0px -50% 0px`, // Margin around the root
};
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.loadImage();
observer.unobserve(entry.target);
}
}, options);
});
observer.observe(this.el.nativeElement);
}
}