捕捉产品印象而不使网站变慢



我在一个网站上工作,我们有数千种产品。我必须捕捉用户在视窗中看到的所有产品的印象。所以我创建了一个directory,我使用了IntersectionObserver,并在产品的HTML代码中引用它。问题是,一旦用户滚动,它就会对移动站点造成性能影响。如何在不减慢网站速度的情况下获得印象?

export class IntersectionObserverDirective
implements OnDestroy, OnInit, AfterViewInit {
@Input() debounceTime = 0;
@Input() threshold = 1;
@Output() visible = new EventEmitter<HTMLElement>();
isSSR: boolean = typeof window === 'undefined';
private observer: IntersectionObserver | undefined;
private subject$ = new Subject<{
entry: IntersectionObserverEntry;
observer: IntersectionObserver;
}>();
constructor(private element: ElementRef) {}
ngOnInit() {
this.createObserver();
}
ngAfterViewInit() {
this.startObservingElements();
}
ngOnDestroy() {
if (this.observer) {
this.observer.disconnect();
this.observer = undefined;
}

this.subject$.next();
this.subject$.complete();  
}
private isVisible(element: HTMLElement) {
return new Promise(resolve => {
const observer = new IntersectionObserver(([entry]) => {
resolve(entry.intersectionRatio === 1);
observer.disconnect();
});
observer.observe(element);
});
}
private createObserver() {
const options = {
rootMargin: '0px',
threshold: this.threshold,
};
const isIntersecting = (entry: IntersectionObserverEntry) =>
entry.isIntersecting || entry.intersectionRatio > 0;
this.observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (isIntersecting(entry)) {
this.subject$.next({ entry, observer });
}
});
}, options);
}
private startObservingElements() {
if (!this.observer) {
return;
}
this.observer.observe(this.element.nativeElement);
this.subject$
.pipe(delay(this.debounceTime), filter(Boolean))
.subscribe(async ({ entry, observer }) => {
const target = entry.target as HTMLElement;
const isStillVisible = await this.isVisible(target);
if (isStillVisible) {
this.visible.emit(target);
observer.unobserve(target);
}
});
}
}

仅在createObserver()中添加超时。像这样。

private createObserver() {
const options = {
rootMargin: '0px',
threshold: this.threshold,
};
let timeouts = {};
const isIntersecting = (entry: IntersectionObserverEntry) =>
entry.isIntersecting || entry.intersectionRatio > 0;
this.observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (isIntersecting(entry)) {
timeouts[entry.target.id] = setTimeout(() => {
this.subject.next({ entry, observer });
}, 500);
}
else {
clearTimeout(timeouts[entry.target.id])
}
});
}, options);
}

Google Analytics拥有强大的滚动触发器,以及许多其他工具。你应该把追踪工作委托给有经验的人。GA更标准,它对客户更有价值,你会更多地了解用户。

如果你讨厌谷歌,必须从头开始发明自己的工具,那就去吧。滚动条和光标每秒触发数千个事件,它们会冒泡到多个元素。使用GA为您的点击和热图!

最新更新