我正在使用IntersectionObserver polyfill延迟加载图块上的图像。
问题是我有数千个磁贴,每个磁贴上都有需要延迟加载的图像。

以前,我仅在滚动停止时使用滚动去抖动器来加载图像,这极大地提高了性能。

问题是如何与IntersectionObserver一起使用滚动防抖器?

一个解决方案但很愚蠢的解决方案是创建可见项的初步数组并添加超时

 let timeoutLastEntities;

 new IntersectionObserver((entries) => {
     setTimeout(function(){
        timeoutLastEntities.add(entities);
      }, 3000);
      // debouncer logic
 }, { threshold: 0.5 }).observe(imageTileElements);

最佳答案

好的,我找到了食谱,但仍然不尽人意

private initializeLazyLoader() {
    this.observer = new IntersectionObserver(
        this.processLazyChanges,
        { threshold: [0.5] }
    );

    // When scroll is triggered
    this.registerIntersectionObserverEvent(this.nativeElement, 'scroll', 300);
}

processLazyChanges(changes: any) {
    changes.forEach((change: any) => {
        var container = change.target;
        $(container).css('border', '1px solid red');
        this.observer.unobserve(container);
    });
}

private registerIntersectionObserverEvent(element: any, event: any, debouncerTime: number) {
    Observable.fromEvent(element, event)
        .debounceTime(debouncerTime)
        .subscribe((event) => this.initializeObservers(event));
}

private initializeObservers(event: any) {
    Array.from(document.querySelectorAll('app-tile')).forEach((tile: any) => {
        this.observer.observe(tile);
    });
}

关于javascript - 观察员去抖动器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43181245/

10-11 14:04