Should I use document.createDocumentFragment or document.createElement

后端 未结 2 994
天涯浪人
天涯浪人 2020-11-28 19:46

I was reading about document fragments and DOM reflow and wondered how document.createDocumentFragment differed from document.createElement as it l

2条回答
  •  一个人的身影
    2020-11-28 20:35

    Another very important difference between creating an element and a document fragment:

    When you create an element and append it to the DOM, the element is appended to the DOM, as well as the children.

    With a document fragment, only the children are appended.

    Take the case of:

    var ul = document.getElementById("ul_test");
    
    
    // First. add a document fragment:
    
    
    (function() {
      var frag = document.createDocumentFragment();
      
      
      var li = document.createElement("li");
      li.appendChild(document.createTextNode("Document Fragment"));
      frag.appendChild(li);
      
      ul.appendChild(frag);
      console.log(2);
    }());
    
    (function() {
      var div = document.createElement("div");
      
      
      var li = document.createElement("li");
      li.appendChild(document.createTextNode("Inside Div"));
       div.appendChild(li);
      
      ul.appendChild(div);
    }());
    Sample List:
    

      which results in this malformed HTML (whitespace added)

      • Document Fragment
      • Inside Div

    提交回复
    热议问题