"异地"复制DOM进行操作 [英] "Offsite" copy of the DOM to do manipulations

查看:106
本文介绍了"异地"复制DOM进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我看了一个关于尼古拉斯·扎卡斯(Nicholas Zakas)的视频讲述了高性能脚本。这一个是关于回流和重绘。他说这是不好的回流,正在移动,改变布局,改变尺寸等。



我回答了一个关于将溢出从一个div转移到另一个 - 我做了什么溢出溢出的内容到其他div是:


  1. 测量内部和外部容器的高度(目前我使用jQuery.height())

  2. 如果内容大于外部

  3. 如果小于(不溢出),结束脚本

  4. 如果更大(溢出),弹出内容器中的最后一个字符,并将前面的div

  5. 将文本放回内容器(导致回流 - 重新计算高度)

  6. 返回步骤1

问题是我正在删除和追加字符,并根据字符弹出出来e容器它也是重新渲染也是每次迭代 - 这使得它有时非常慢。



有一种方法来拥有DOM的JS副本来操纵,检查高度等。 ?我正在寻找的就像一个页面的克隆。我听说过DOM片段,但它只是将节点放入DOM之前的一个容器。

解决方案

DOM的副本,以下方法可以有用:




  • document.createDocumentFragment() - 创建一个简单的节点存储对象。

  • document.implementation.createDocument DOMParser - 创建并处理完整的文档。

  • cloneNode - 复制一个节点(使用 appendChild replaceChild )。



    • 这些方法对DOM结构非常有用,但不幸的是,它们不会返回尺寸的有用值。



      元素必须呈现。这可以通过创建< iframe> 元素来完成,并将文档(节点)插入其中。前面提到的方法可以用于此目的:创建文档的一部分的有效副本,并将文档插入iframe。



      这可能是有用的还要插入 < base> 元素在< head> 中,以便URL和图像被正确解析。


      I have recently watched a video of Nicholas Zakas talk about high performace scripts. This one is about reflow and repaint. he says it's bad to constantly reflow which is moving around and changing the layout, change dimensions, etc.

      i answered a question about Transfer overflow from one div to another - what i did to "spill" overflowing content to the other div was:

      1. measure the height of the inner and outer container (currently, i use jQuery.height())
      2. check if inner is greater than outer
      3. if less than (no spill), end script
      4. if greater (spill), pop the last character in the inner container and prepend to the next div
      5. put the text back in the inner container (causing reflow - recalculating heights)
      6. back to step 1

      the problem is i am removing and appending characters, and measuring the height of the spilled container per "character popped" out of the container. it's re-rendering also per iteration - which makes it super slow at times.

      is there a way to have a JS copy of the DOM to manipulate, check height etc.? what i'm looking for is like a clone of the page. i have heard of DOM fragments but it's just a container for nodes before placing them into the DOM.

      解决方案

      When thinking about creating a copy of the DOM, the following methods can be useful:

      These methods are very useful for DOM structures, but unfortunately, they do not return useful values for dimensions.

      The elements have to be rendered. This can be done by creating an <iframe> element, and insert the document (nodes) in it. The previously mentioned methods can be used for this purpose: Create an effective copy of (part of) the document, and insert the document into the iframe.

      It might be useful to also insert a <base> element in the <head>, so that URLs and images are correctly resolved.

      这篇关于&QUOT;异地&QUOT;复制DOM进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆