Created
May 24, 2021 11:52
-
-
Save martinsotirov/d2fe275eaa0760d4d623fba1419e1b3d to your computer and use it in GitHub Desktop.
Prefetch Angular Content
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
/** | |
* Kudos to https://timdeschryver.dev/blog/making-your-application-feel-faster-by-prefetching-data-with-ngrx | |
*/ | |
@Directive({ | |
selector: '[prefetch]', | |
}) | |
export class PrefetchDirective implements OnInit, AfterViewInit, OnDestroy { | |
@Input() | |
prefetchMode: ('load' | 'hover' | 'visible')[] = ['visible'] | |
@Output() | |
prefetch = new EventEmitter<void>() | |
observer: IntersectionObserver | |
loaded = false | |
constructor(private elemRef: ElementRef) {} | |
ngOnInit() { | |
if (this.prefetchMode.includes('load')) { | |
this.prefetchData() | |
} | |
} | |
ngAfterViewInit() { | |
this.observer = new IntersectionObserver((entries) => { | |
entries.forEach((entry) => { | |
if (entry.isIntersecting) { | |
this.prefetchData() | |
this.observer.disconnect() | |
} | |
}) | |
}) | |
this.observer.observe(this.elemRef.nativeElement) | |
} | |
ngOnDestroy() { | |
if (this.observer) { | |
this.observer.disconnect() | |
} | |
} | |
@HostListener('mouseenter') | |
onMouseEnter() { | |
if (!this.loaded && this.prefetchMode.includes('hover')) { | |
this.loaded = true | |
this.prefetchData() | |
} | |
} | |
prefetchData() { | |
if (navigator.connection.saveData) { | |
return undefined | |
} | |
this.prefetch.next() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment