显示多个元素时性能不佳 [英] Poor performance when displaying multiple elements

查看:59
本文介绍了显示多个元素时性能不佳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在搜索页面上工作,该页面允许过滤,搜索和分页结果列表。每次更改当前显示项目的列表时,淘汰会花费大量时间来呈现新值。我的淘汰知识是有限的,但我可以在DevTools中看到事情的处理效率非常低:

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:


  • 为每个元素解析项目模板(没有模板缓存?)

  • 每个项目分别插入DOM(没有批量操作?)

您有解决这些问题的建议吗?

Do you have any suggestions for fixing these issues?

我试图提取相关代码:

$.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
}

相关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>


推荐答案

答案是避免使用模板绑定。它触发了多个昂贵的 jQuery.parseHTML 调用。

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

慢代码:

  <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>

快速代码:

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




  • JS Bin示例

  • JS Perf

    • JS Bin example.
    • JS Perf
    • 这响应没有回答如何将DOM操作保持在最低限度,我会问另一个更具体的问题。

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

      这篇关于显示多个元素时性能不佳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆