Knockout.js is very slow foreach

I am trying to create simple markup using templates. Sort of:

<div class="list" data-bind="template: {name: 'mytemplate', data: someData}"></div> <script id="mytemplate"> <div class="item" data-bind="text: someText"></div> </script> 

This works very well, but if I need to display a lot of divs with these templates, it will be very slow. Knockout after creating each div adds it to the document. But if I do something like this:

 el = document.createElement("div"); applyBindings(myModel, el); (div.list).innerHTML = el.innerHTML 

It works much faster, but inconvenient.

Maybe Knockout has a built-in function to create a group of elements and then add this group to the document?

+6
source share
2 answers

KO seems to be manipulating the DOM with every added DIV. Bypassing the DOM is expensive and slows down the rendering of your page. There is an open question for KO Github: https://github.com/SteveSanderson/knockout/issues/248

In my opinion, Knockout is currently not up to the task of processing large foreach datasets. Performance in Chrome is decent (because Chrome is awesome), but pretty poor in Internet Explorer (and even worse in older IE): http://jsfiddle.net/StarcounterJack/FgSCw/

Instead of using Knockout, try a manual approach: first create a DIV in memory and immediately insert them into the DOM. This is what you do in your second example with document.createElement (). With jQuery you can do this:

 var newDiv = $("<div>my new div</div>"); var newDiv2 = $("<div>my new div2</div>"); newDiv.append(newDiv2); $('body').append(newDiv); //only this last step traverses the DOM 

For templates, I prefer to use Mustache.js, download templates using the John Resig utility <head><script type="text/templates"> enable the template, and take care of rendering manually through my own JavaScript. You have more control over how these elements are rendered, and you can try different approaches when dealing with performance issues such as the one you have.

+6
source

The best solution right now could be my quick knockout plugin .

It has O(1) inserts and deletes among other functions to make it noticeably fast (i.e. faster than one could do on its own).

This is a strong competitor to replace the current foreach binding in KO 3.5 (or 3.6).

+2
source

Source: https://habr.com/ru/post/921872/


All Articles