Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append clone or create DOM on the fly - What is better?

Tags:

jquery

I wish to make the following list from an array returned from an ajax call.

<ul id="list">
  <li><input type="checkbox" name="rss" value="231" />bla</li>
  <li><input type="checkbox" name="rss" value="321" checked="checked" />ble</li>
  <li><input type="checkbox" name="rss" value="431" />abc</li>
</ul>

Both of the following will work (I might need to tweak but they are close. Is one method preferred over the other? Is there something better altogether? Thanks

var l=$("#list");
l.html('');
$(data).each(function(){
  l.append('<li><input type="checkbox" name="rss" checked="'+((this.selected)?'checked':null)+'" value="'+this.id+'" />'+this.channel+'</li>');
  //Or
  l.append($("#rss-clone").clone(true).removeAttr('id').find('input').val(this.id).attr('checked',(this.selected)?'checked':null).parent().text(this.channel));
},'json');

//required for clone solution only:

<ul class="hidden"><li id="rss-clone"><input type="checkbox" name="rss" value="" />bla</li></ul>
    like image 328
    user1032531 Avatar asked Aug 19 '12 12:08

    user1032531


    1 Answers

    See also: jQuery and dynamic elements vs display css attribute

    The takeaway is that dynamically creating doms on the fly adds overhead on the client, whereas cloning existing doms is fast on the client but has the overhead of having to render and download them in advance.

    None is the better than the other, which one is more suitable for you depends on your project; if you care more about client performance than a few extra bytes to be downloaded per request you would do good choosing the cloning method for instance.

    As far as I can tell however, the client performance is not severely affected by any of the methods, cloning is ever so slightly faster but dynamically creating elements is not horribly slow by any means. Unless you are creating 100s of these the choice may just come down to a matter of taste, ie what feels better for you.

    One thing to note however is that unless you need to create many very different elements, cloning is a more convenient method in that you can easily style and modify the elements afterwards if the markup is not embedded in your JS code.

    like image 112
    Mahn Avatar answered Oct 18 '22 10:10

    Mahn