Angular Web Components批量渲染性能优化求助
问题:Angular Elements Web Components 批量渲染性能优化
我使用Angular的elements包开发全站复用的Web Components,某次API调用需一次性渲染约2000个该组件,耗时约2秒,但渲染同等数量的简单<div>几乎瞬间完成。
批量渲染模拟代码
const output = document.querySelector('#output'); let componentBadge = ''; for (let i = 0; i < 2000; i++) { componentBadge += `<custom-badge>${i}</custom-badge>`; } output.innerText = componentBadge;
已尝试的优化手段
- 将组件的
encapsulation设置为Emulated、None及ShadowDom - 将
changeDetection策略设置为ChangeDetectionStrategy.OnPush
补充说明
有人建议使用cdk-virtual-scroll-viewport,但该组件需要完整的Angular上下文,而我使用的是简单LAMP栈,生成的HTML中包含大量Angular Web Components,示例结构如下:
<table> <tbody> <tr><td><custom-badge>1</custom-badge></td></tr> <tr><td><custom-badge>2</custom-badge></td></tr> ... <tr><td><custom-badge>n</custom-badge></td></tr> </tbody> </table>
在此场景下无法使用*ngFor或*cdkVirtualFor等模板指令。
我尝试开发了一个基于CDK虚拟滚动的virtual-scroll Web Component,通过HTML插槽控制元素的添加与移除:
<virtual-scroll number-of-elements="n"> <custom-badge slot="index-1">1</custom-badge> <custom-badge slot="index-2">2</custom-badge> ... <custom-badge slot="index-n">n</custom-badge> </virtual-scroll>
该组件内部渲染逻辑:
<cdk-virtual-scroll-viewport itemSize="20"> <ng-container *cdkVirtualFor="let element of elements(); trackBy: trackBy"> <div> <slot name="index-{{element}}"></slot> </div> </ng-container> </cdk-virtual-scroll-viewport>
组件代码:
@Component({ templateUrl: './virtual-scroll.component.html', styleUrl: './virtual-scroll.component.scss', encapsulation: ViewEncapsulation.ShadowDom, }) export class VirtualScrollComponent { @Input({ required: true }) public set numberOfElements( n: number ) { const elements = Array.from({length: n}).map((_, i) => i); this.elements.set(elements); } protected elements: WritableSignal<number[]> = signal([]); protected trackBy(index: number, value: number): number { return value; } }
此方案性能略有提升,但仍不理想,因为即便组件未渲染到屏幕,也已被创建。
请问还有哪些优化手段可以提升Web Components的渲染性能?
内容的提问来源于stack exchange,提问作者Jeroen1602
相关产品推荐
相关产品推荐

