Skip to content

Instantly share code, notes, and snippets.

@martinsotirov
Created May 24, 2021 11:52
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 martinsotirov/d2fe275eaa0760d4d623fba1419e1b3d to your computer and use it in GitHub Desktop.
Save martinsotirov/d2fe275eaa0760d4d623fba1419e1b3d to your computer and use it in GitHub Desktop.
Prefetch Angular Content
/**
* 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