首页 > 解决方案 > Angular2 [style.width] 绑定高 CPU 使用率

问题描述

我目前正在为 Angular (6.0) 集成一个顶栏进度指示器。

我尝试了多个 npm 包,但是一旦我启动进度加载器,所有包都会受到高 CPU 使用率的影响。

Chrome 任务管理器报告 50-80% 的 CPU 使用率。这是以下包中的一个最小示例:https ://github.com/aitboudad/ngx-loading-bar

模板:

<ng-container *ngIf="(loader.progress$|async) as progress">
    <div class="bar" [style.width.%]="progress">        
    </div>
</ng-container>

服务:

@Injectable()
export class LoadingBarService implements OnDestroy {
  readonly progress$ = (new Subject<number>()).pipe(debounceTime(0)) as Subject<number>;

  private _pendingRequests = 0;
  private _value = 0;
  private _incTimeout: any;

  start(initialValue = 2) {
    ++this._pendingRequests;
    if (this._value === 0 || this._pendingRequests === 1) {
      this.set(this._pendingRequests === 1 && this._value > 0 ? this._value : initialValue);
    }
  }

  set(n) {
    if (n === 0 && this._pendingRequests > 0) {
      n = 2;
    }

    this._value = n;
    this.progress$.next(n);

    if (this._pendingRequests === 0) {
      return;
    }

    clearTimeout(this._incTimeout);
    if (this._value > 0 && this._value < 100) {
      this._incTimeout = setTimeout(() => this.increment(), 250);
    }
  }
}

如您所见,该值仅每 250 毫秒更新一次。但 CPU 使用率始终保持在 ~60-70%(一个核心)。

当我删除绑定[style.width.%]时,CPU 使用率下降到 5-10%。

更新样式宽度真的那么昂贵吗?

有没有更好(更快)的方法来更新样式的宽度?

因为在显示加载程序时 CPU 使用率如此之高会损害导航页面时的用户体验。

标签: cssangularangular2-templateangular2-services

解决方案


我注意到我两次导入了 LoadingBarModule(在主模块和组件模块中)。从组件模块中删除导入解决了这个问题。


推荐阅读