Why Does Setting Textcontent Cause Layout Thrashing?
Solution 1:
The issue:
You are correct! Just like you observed. Setting textContent
does cause thrashing.
Here is what the DOM specification has to say:
textContent of type DOMString, introduced in DOM Level 3
This attribute returns the text content of this node and its descendants. When it is defined to be null, setting it has no effect. On setting, any possible children this node may have are removed and, if it the new string is not empty or null, replaced by a single Text node containing the string this attribute is set to.
The fix
A non thrashing way would be to get the element's text nodes and modify those instead of using textContent
or innerText
(which is non standard).
var test = document.getElementById("test");
var a = document.createTextNode("");
test.appendChild(a);
setInterval(function(){
a.nodeValue = "Test test test";
},100);
Here is a working fiddle
Of course if the actual text will change, a paint will have to occur to update what you're seeing.
Solution 2:
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 propertycontain: 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:
Post a Comment for "Why Does Setting Textcontent Cause Layout Thrashing?"