Angular类绑定调用isTouching高频触发,如何实现200ms节流优化性能
优化方案
1. 移除模板中的方法调用,手动维护状态变量
Angular每次运行变更检测时,都会执行模板内绑定的方法,这是isTouching被触发数百次的核心原因。优化思路是把计算结果存在组件的本地布尔变量中,模板直接绑定变量,仅在会影响元素位置的事件(滚动、窗口resize)触发时才重新计算状态,从根源上减少无效执行。
模板修改后代码:
<div #mobileTrialSection class="mobile-trial-section hidden-lg hidden-xl" [class.is-touching]="isMobileTrialTouching"> <div class="heading">Your trial. Free and easy.</div> <ul class="features"> <li>Full access for 14 days</li> <li>No credit card required</li> </ul> </div>
2. 基于RxJS实现事件节流(推荐)
用RxJS封装事件流,自带节流操作符,代码更简洁,也方便统一管理订阅销毁,避免内存泄漏,组件内实现代码如下:
import { Component, ViewChild, ElementRef, AfterViewInit, OnDestroy } from '@angular/core'; import { fromEvent, Subject } from 'rxjs'; import { throttleTime, takeUntil } from 'rxjs/operators'; // 组件类内部代码 isMobileTrialTouching = false; @ViewChild('mobileTrialSection') mobileTrialSection!: ElementRef<HTMLElement>; private destroy$ = new Subject<void>(); ngAfterViewInit() { // 监听滚动事件,200ms节流 fromEvent(window, 'scroll').pipe( throttleTime(200), takeUntil(this.destroy$) ).subscribe(() => this.updateTouchingState()); // 监听窗口大小变化事件,200ms节流 fromEvent(window, 'resize').pipe( throttleTime(200), takeUntil(this.destroy$) ).subscribe(() => this.updateTouchingState()); // 初始化时计算一次初始状态 this.updateTouchingState(); } private updateTouchingState() { const el = this.mobileTrialSection.nativeElement; this.isMobileTrialTouching = this.utils.isTouching(el, null, 100); } ngOnDestroy() { // 销毁订阅避免内存泄漏 this.destroy$.next(); this.destroy$.complete(); }
3. 预封装节流版本的工具方法
如果该工具方法需要在多个组件复用,可以直接在utils中提前封装节流后的版本,注意要保证节流函数实例唯一,不要每次调用都重新生成:
// utils类内部代码 import { throttle } from 'lodash'; // 也可以用自己实现的节流函数 // 提前封装节流版本,200ms节流 const throttledIsTouching = throttle(isTouching, 200, { leading: true, trailing: true }); export const utils = { isTouching, throttledIsTouching // 其他工具方法 }
如果临时用这个方案,模板可以直接绑定[class.is-touching]="utils.throttledIsTouching( mobileTrialSection, null, 100 )",但还是更推荐第一种方案,彻底避免变更检测带来的无效调用。
注意事项
- 要等
ngAfterViewInit生命周期触发后再操作DOM,避免拿不到元素引用报错 - 所有事件订阅都要在
ngOnDestroy中取消,避免内存泄漏 - 如果有多个元素需要做同类检测,不要给每个元素单独绑定滚动监听,统一用一个全局滚动监听批量更新所有元素的状态,进一步降低性能消耗
内容的提问来源于stack exchange,提问作者Yousaf Raza
相关产品推荐
相关产品推荐

