【发布时间】:2018-07-24 17:50:27
【问题描述】:
我目前正在为 Angular (6.0) 集成一个顶栏进度指示器。
我尝试了多个 npm 包,但是一旦我启动进度加载器,所有包都会受到高 CPU 使用率的影响。
Chrome 任务管理器报告 CPU 使用率为 50-80%。这是来自以下包的一个最小示例: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 使用率如此之高会损害用户在导航页面时的体验。
【问题讨论】:
标签: css angular angular2-template angular2-services