JavaScript DocumentFragment

    技术2022-07-11  124

    One of the lessor known but incredibly useful gems within JavaScript is the DocumentFragment.  DocumentFragments allow developers to place child elements onto an arbitrary node-like parent, allowing for node-like interactions without a true root node.  Doing so allows developers to produce structure without doing so within the visible DOM -- an increase of speed is the true advantage.  Let me show you how DocumentFragments are used!

    DocumentFragment是JavaScript中最鲜为人知但有用的宝石之一。 DocumentFragments允许开发人员将子元素放在任意类似节点的父节点上,从而无需真正的根节点即可进行类似节点的交互。 这样做使开发人员无需在可见的DOM内即可生成结构- 速度的提高才是真正的优势 。 让我向您展示如何使用DocumentFragments!

    DocumentFragment示例 (DocumentFragment Example)

    Let's start with a UL with which we'll inject LI's to:

    让我们从UL入手,我们将使用LI注入:

    <ul id="list"></ul>

    DOM injections and modifications are taxing, so the fewer the interactions the better;  that's where the DocumentFragment comes in.  The first step is creating the DocumentFragment:

    DOM注入和修改很费力,因此交互越少越好; 这就是DocumentFragment的来源。第一步是创建DocumentFragment:

    // Create the fragment var frag = document.createDocumentFragment();

    This DocumentFragment act like a pseudo-DOM node -- think of it as a virtual UL element, in this case.  Now it's time to add elements:

    该DocumentFragment的作用类似于伪DOM节点-在这种情况下,请将其视为虚拟UL元素。 现在是时候添加元素了:

    // Create numerous list items, add to fragment for(var x = 0; x < 10; x++) { var li = document.createElement("li"); li.innerHTML = "List item " + x; frag.appendChild(li); }

    Elements can be added to the DocumentFragment just as you could a normal DOM node.  Once the tree of DOM nodes is ready to hit the page, simply place the DocumentFragement into its parent (or other DOM placement functions):

    可以像普通DOM节点一样将元素添加到DocumentFragment中。 一旦DOM节点树准备好进入页面,只需将DocumentFragement放入其父级(或其他DOM放置函数)中:

    // Mass-add the fragment nodes to the list listNode.appendChild(frag);

    Using DocumentFragments is faster than repeated single DOM node injection and allows developers to perform DOM node operations (like adding events) on new elements instead of mass-injection via innerHTML.  Keep DocumentFragment close by when performing lots of DOM operations -- it could speed up your app considerably!

    使用DocumentFragments比重复单个DOM节点注入更快,并且允许开发人员对新元素执行DOM节点操作(例如添加事件),而不是通过innerHTML进行大规模注入。 在执行许多DOM操作时,请保持DocumentFragment靠近-这可以大大加快您的应用程序的速度!

    翻译自: https://davidwalsh.name/documentfragment

    相关资源:JavaScript Tips 使用DocumentFragment加快DOM渲染速度
    Processed: 0.012, SQL: 9