我有一个输入框来接受 searchTerm
输入。每个 <tr>
都附有指令.它负责搜索并突出显示下表中的任何匹配文本。
<table>
<tr *ngFor="let car of cars, index as i" [highlight]="searchTerm">
<td>{{ car?.name}}</td>
<td>{{ car?.color}}</td>
<td>{{ car?.origin}}</td>
<td>{{ car?.owner}}</td>
</tr>
</table>
该指令包含循环遍历 <tr>
的脚本并深入 <td>
搜索(使用正则表达式)匹配文本并附加高亮范围类。
const highlightSpanTag1 = '<span class="highlight">';
const highlightSpanTag2 = '</span>';
// regexp search ....
// appending highlightSpanTag1/highlightSpanTag2 between matching text
newInnerHtml += .....
下面的指令脚本:
@Directive({
selector: '[highlight]'
})
public search(): void {
const attachedNode = this.hostEl.nativeElement; // =====> this is <tr> //
attachedNode.children.forEach((childNode) => {
this.highlight(childNode); // =====> this is <td> //
});
}
private highlight(childNode): void {
...
...
childNode.innerHTML = newInnerHtml; // =====> this is going to execute when searchTerm change, causing some bad performance issues
}
当我有数百个表行时,我可以在调试控制台中看到性能下降并且 CPU 使用率超过 99%。我发现这一行 childNode.innerHTML
是问题所在。如何避免这种情况?
我的第一个想法是在 requestAnimationFrame(this.highlight.bind(this))
上进行测试但这没有帮助。
最佳答案
查看 ngx-bootstrap 组件的源代码
他们使用
<span [innerHtml]="highlight(match, query)">
并且在 TypeScript 中有高亮功能。
与渲染 DOM 和修改 DOM 相比,这将更高效地生成 html。
那么试试
<table>
<tr *ngFor="let car of cars, index as i">
<td [innerHtml]="hightlight(car?.name, searchTerm)"></td>
<td [innerHtml]="hightlight(car?.color, searchTerm)"></td>
<td [innerHtml]="hightlight(car?.origin, searchTerm)"></td>
<td [innerHtml]="hightlight(car?.owner, searchTerm)"></td>
</tr>
</table>
然后将您的突出显示代码放入您的 TypeScript 中。
关于javascript - 使用 Angular4 直接更新到 innerHTML 时如何提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53604693/