Joseph
Joseph

Reputation: 119837

"Offsite" copy of the DOM to do manipulations

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.

Upvotes: 2

Views: 379

Answers (1)

Rob W
Rob W

Reputation: 348972

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.

Upvotes: 1

Related Questions