javascript - IntersectionObserver 去抖器

标签 javascript optimization lazy-loading

我正在使用IntersectionObserver polyfill在图 block 上延迟加载图像。 问题是我有几千个图 block ,每个图 block 上都有一个需要延迟加载的图像。

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

问题是如何将滚动去抖动器与 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 - IntersectionObserver 去抖器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43181245/

相关文章:

使用 ng-include 包含的 html 文件中的 JavaScript 不执行

javascript - 从 URL 中完全删除哈希值

javascript - typescript 中的字符串枚举

c++ - 在汇编代码中寻找不必要的缓冲区拷贝

java - @Basic(fetch = FetchType.LAZY) 不起作用?

objective-c - 在 Objective-C 中使用延迟加载覆盖属性 getter

javascript - 通过onClick事件打开特定组件 - REACT.JS

mysql - 如何基于解释/索引提高查询性能

c# - 从此方法返回的最佳对象 asp.net csharp

ios - 使用延迟加载在 ScrollView 上加载图像