Poor performance when displaying multiple elements

2019-04-13 10:56发布

I work on a search page that allows filtering, searching and paginating through the list of results. Each time list of currently displayed items is changed, knockout takes a lot of time to render new values. My knockout knowledge is limited but I can see in the DevTools that things are being handled very inefficiently:

  • item template is parsed for each element (no template caching?)
  • each item is inserted into the DOM separately (no bulk operations?)

Do you have any suggestions for fixing these issues?

Knockout rendering list with multiple elements.

I tried to extract the relevant code:

$.get("/api/Search/GetSearchResults?page=" + bla)
           .then(function (result) {
               self.contentListViewModel.load(result.SearchHits);
               //...
           });

//----------------
var ContentListViewModel = function (options) {
    self.searchHits = ko.observableArray([]);
    //...
    this.load = function (elements) {
        for (var i = 0; i < elements.length; i++) {
            elements[i] = new ContentElementViewModel(elements[i]);
            //...
        }
        self.searchHits(elements);
    }
}

//----------------
var ContentElementViewModel = function (dto, options) {
  //just setting couple of observable variables and couple of methods
}

Relevant HTML:

<ul data-bind="foreach: { data: searchHits, afterRender: afterRenderSearchHits }, as: &#39;hit&#39;, masonry: { enable: true, hits: searchHits }, css: { &#39;listify&#39;: !pinterestEnabled() }">
    <li data-bind="template: { name: $data.template() }"></li>
</ul>

1条回答
【Aperson】
2楼-- · 2019-04-13 11:21

The answer is to avoid using 'template' binding. It triggers multiple jQuery.parseHTML calls that are expensive.

Slow code:

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

Fast code:

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

This response does not answer how to keep DOM manipulation to minimum, I'll ask another, more specific question for that.

查看更多
登录 后发表回答