代码之家  ›  专栏  ›  技术社区  ›  Matrym

jquery克隆性能

  •  3
  • Matrym  · 技术社区  · 16 年前

    I've read that javascript gets significant performance benefits from modifying off-dom. Earlier today, I was reading the clone documentation:

    “请注意,使用.clone()时 method, we can modify the cloned 元素或其之前的内容 (重新)将它们插入 文件。”

    Is the implication then that if I have 1,000 LI's and I want to make a change across all of them, the most efficient method would be to clone it, modify the clone, destroy the original, and place the clone?

    你将如何以最有效的方式进行修改?

    3 回复  |  直到 16 年前
        1
  •  3
  •   Mark    16 年前

    detach()方法是为您正试图执行的操作而设计的方法:

    http://api.jquery.com/detach/

    Edit: It's worth a mention that everyone do their own profiling/tests, which is good, common sense advice. Plus it's fun to see the ridiculous performance gains you'll get. :)

    My rule of thumb is this: If you're doing manipulations on many elements that involves adding or removing or moving elements around, you should absolutely use .detach(), if you're doing something like addClass, don't use detach.

    If you're unsure about specific manipulations or how many qualifies as 'many', you should run a test.

    下面是我在这个问题的辩论中做的一个简单比较: http://jsbin.com/uwode3/5 VS http://jsbin.com/uwode3/4

        2
  •  6
  •   Community Mohan Dere    9 年前

    Actually, the implication is that it would be more efficient to modify cloned elements before inserting them into the DOM than to insert the cloned elements into the document 然后修改它们 . Whether or not clone-modify-replace is more efficient than simply modifying the elements in-place will likely depend a 许多 关于你打算做什么修改…一如既往, 分析您的代码 然后根据实际数据选择最能满足您需求的选项。

    …当你在做的时候…您可以直接“分离”一个dom元素:只需调用 removeChild() (或者,由于您使用jquery, detach() ) - the element will still exist as long as you retain a reference to it, and can be re-inserted after you're done making modifications.

    ...Oh, and regardless of which technique you end up using, you'll almost certainly see better results from removing the parent UL than from removing each of the 1K child LI elements, one at a time...

        3
  •  2
  •   Mewp    16 年前

    还有一种更有效的方法: .detach() 从树中修改它们,然后重新插入。
    However, if you only modify properties of the DOM objects, and not read them, you shouldn't trigger a reflow (which is the slow operation) anyway, at least not in firefox (from what I've read). Though detaching them, and then reattaching makes sure that there are at most two reflows.