Why does setting textContent cause layout thrashing?

后端 未结 2 765
忘掉有多难
忘掉有多难 2021-02-01 06:30

This blog post suggests that textContent is preferable to innerText for avoiding layout thrashing. But it is focused on retrieving an element\'s text;

2条回答
  •  天涯浪人
    2021-02-01 07:10

    In addition to Benjamin answer, I noticed that when the value of nodeValue or innerText is different than the previous one, the entire document layout is trashed too, as you can see here: http://jsfiddle.net/5N7Rr/15/

    (Full screen, open in new tab)

    The browser trashes the entire layout because he don't knows the size of the element, so the trick to avoid entire document trashing is to set a fixed height and width AND set overflow to hidden (Important). This way you tell the browser that whatever the content of the element is, it never is going to exit the element boundaries.

    EDIT 30/11/2020: I also needed to add CSS property contain: strict to explicitly tell the browser that the content is not going to exit the container.

    Fiddle: http://jsfiddle.net/u9pra25f/

    And proof (Full screen again). Notice how the layout update only affects the element:

提交回复
热议问题