createElement + createTextNode oneliner?

前端 未结 3 1594
星月不相逢
星月不相逢 2021-02-06 07:45

I\'m adding a few thousand rows to a table so i need the speed of native javascript for this one.

Currently I\'m using:

nThName = document.createElement(         


        
3条回答
  •  一向
    一向 (楼主)
    2021-02-06 08:14

    So, you're looking for performance? One-liners don't help with that. Using document fragments and cloning nodes does help, however. But it requires a bit more code.

    var table = document.getElementById('t');
    var tr = table.querySelector('tr');
    var th = document.createElement('th');
    var clone;
    
    var df = document.createDocumentFragment();
    
    for (var i = 0; i < 100; i++) {
        // Performance tip: clone a node so that you don't reuse createElement()
        clone = th.cloneNode();
        clone.appendChild(document.createTextNode('hello' + i));
    
        // Performance tip: append to the document fragment
        df.appendChild(clone);
    }
    
    // Performance tip: append only once in the real DOM
    tr.appendChild(df);
    

    See jsfiddle demo: http://jsfiddle.net/3KGwh/3/

    Document fragments are basically mini-DOM, with limited methods. They're great because they allow you to get great performance, and you can append a single element to the real DOM.

提交回复
热议问题