You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 07:45:21