jquery: fastest DOM insertion?

后端 未结 8 1449
长情又很酷
长情又很酷 2020-12-04 16:45

I got this bad feeling about how I insert larger amounts of HTML. Lets assume we got:

var html=\"

....
\"
相关标签:
8条回答
  • 2020-12-04 17:41

    The fastest way to append items

    The fastest way to append to the DOM tree is to buffer all of your append in to a single DOM fragment, then append the dom fragment to the dom.

    This is the method I use in my game engine.

    //Returns a new Buffer object
    function Buffer() {
    
        //the framgment
        var domFragment = document.createDocumentFragment();
    
        //Adds a node to the dom fragment
        function add(node) {
            domFragment.appendChild(node);
        }
    
        //Flushes the buffer to a node
        function flush(targetNode) {
    
            //if the target node is not given then use the body
            var targetNode = targetNode || document.body;
    
            //append the domFragment to the target
            targetNode.appendChild(domFragment);
    
        }
    
        //return the buffer
        return {
            "add": add,
            "flush": flush
        }
    }
    
    
    //to make a buffer do this
    var buffer = Buffer();
    
    //to add elements to the buffer do the following
    buffer.add(someNode1);
    
    //continue to add elements to the buffer
    buffer.add(someNode2);
    buffer.add(someNode3);
    buffer.add(someNode4);
    buffer.add(someN...);
    
    //when you are done adding nodes flush the nodes to the containing div in the dom
    buffer.flush(myContainerNode);
    

    Using this object i am able to render ~1000 items to the screen ~40 times a second in firefox 4.

    Here's a use case.

    0 讨论(0)
  • 2020-12-04 17:45

    Try the following:

    $("#mydiv").append(html);
    

    The other answers, including the accepted answer, are slower by 2-10x: jsperf.

    The accepted answer does not work in IE 6, 7, and 8 because you can't set innerHTML of a <table> element, due to a bug in IE: jsbin.

    0 讨论(0)
提交回复
热议问题