2

Currently when I insert a list of views in backbone I do :

    var jqGuestList = $("#guestList");
    jqGuestList.empty();

    items.each(function(item){
        var view = new wedapp.view.GuestItem({
            model: item,
            collection: this.collection
        });

        jqGuestList.append(view.render().el);
    });

This however cause my a great deal of pain, adding each one manually to the DOM is slow as hell, specially on mobile but even on desktop..

is there a way to insert all the views in one jqGuestList.html(views) instead?

The Orca
  • 1,250
  • 2
  • 17
  • 31

1 Answers1

5

You could use a Document Fragment http://ejohn.org/blog/dom-documentfragments/

var jqGuestList = $("#guestList");
jqGuestList.empty();

var frag = document.createDocumentFragment();
items.each( function(item) {
    var view=new wedapp.view.GuestItem({model:item});
    frag.appendChild(view.render().el);
});

jqGuestList.append(frag);

You should see some improvement.

nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • Yea I was wondering about those, is it really faster than adding to the dom directly if you saved the node? – The Orca Jan 02 '12 at 15:52
  • reading from the doc it seems it will only trigger only one reflow from the browser, definitely a big improvement – The Orca Jan 02 '12 at 15:53
  • Some interesting discussion about this. I've been wondering the benefits myself. [Does using a document fragment really improve performance](http://stackoverflow.com/questions/14203196/does-using-a-document-fragment-really-improve-performance) – jmk2142 Jul 24 '14 at 10:16
  • @orangewarp The key is to work with a detached node to avoid browser reflows. Fragments will do, but you could also use a new jQuery object or a node you explicitly detached. – nikoshr Jul 24 '14 at 12:03