简体   繁体   English

如何通过减少DOM操作来提高性能?

[英]How to improve performance by reducing DOM manipulation?

In the simple example below, Knockout calls HTMLElement.appendChild 18 times to render the template. 在下面的简单示例中,Knockout调用HTMLElement.appendChild 18次以呈现模板。 It doesn't use DocumentFragment , so each of these 18 operations are made on the live DOM causing reflows. 它不使用DocumentFragment ,因此这18个操作中的每一个都在live DOM上进行,导致回流。 Ideally, there should be only one call to appendChild on the live DOM. 理想情况下,在live DOM上只应该调用appendChild

This really hurts performance, does anyone know how to reduce the damage? 这真的会伤害性能,有谁知道如何减少伤害?


JS BIN with the code. JS BIN与代码。


JavaScript JavaScript的

var viewModel = {
  people:[
    {name: 'Tim'},
    {name: 'John'},
    {name: 'Greg'}
  ]
};

ko.applyBindings(viewModel, document.getElementById('list1'));

HTML HTML

<ul id='list1' data-bind="foreach: { data: people }">
  <li>
      <h3 data-bind="text: name"></h3>
  </li>
</ul>

My Repeat plugin provides a binding that can be used as an alternative to the foreach binding. My Repeat插件提供了一个绑定,可以用作foreach绑定的替代方法。 It's faster in many cases, so you'll just need to experiment to compare the performance. 在许多情况下它更快,因此您只需要进行实验来比较性能。

For comparison, here's how you'd bind your example using repeat : 为了比较,以下是使用repeat绑定示例的方法:

<ul id='list1'>
  <li data-bind="repeat: people">
    <h3 data-bind="text: $item().name"></h3>
  </li>
</ul>

http://jsbin.com/lizi/7/edit http://jsbin.com/lizi/7/edit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM