简体   繁体   中英

Is it imperformant to adjust a box height dynamically in complex DOM?

Quick summary: We have a sidebar in our web shop. There are three boxes stacked upon each other. Each of these show something like a slideshow of products (a picture of it, the name and the price information). The height of these slides vary. The slides loop from product to product every few seconds and the height of the containing box adjusts automatically.

Is it true that all the enclosing elements in the DOM and so the whole page layout needs to be recalculated and thus rerendered?

When does reflow happen in a DOM environment?

According to that previous question,

When you add or remove a DOM node.

When you apply a style dynamically (such as element.style.width="10px").

...a DOM reflow occurs (you will suffer a slight penalty).

What is a "reflow"?

Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. ( https://developers.google.com/speed/articles/reflow )

If the height of the containing box is "adjusting automatically," you are probably either:

  • Adding an image to the "slide", which counts as an "addition of a DOM node".
  • Setting an image as a CSS background to an element and adjusting that element's dimensions with a "dynamic style".

In both cases, according to the cited question, you would qualify for a reflow.

It'd be best to keep your DOM interactions to a minimum for performance's sake. Giving these boxes a fixed size, and using CSS to center/fit your images nicely, would be wise.

While this may not be a good idea in most cases, you could also follow Google's advice:

If you make complex rendering changes such as animations, do so out of the flow. Use position-absolute or position-fixed to accomplish this.

But absolute-ing or fixed-ing your elements may quickly make your CSS a tangled mess. Use with caution.

And also, use common sense when dealing with the DOM; avoid performing expensive tasks, but don't get too caught up in optimizations, either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM