简体   繁体   中英

Why does setting textContent cause layout thrashing?

This blog post suggests that textContent is preferable to innerText for avoiding layout thrashing. But it is focused on retrieving an element's text; for setting element text, the opposite appears to be true -- at least in the following example.

This example uses innerText and produces no layout thrashing:

<style>
    #test {
        background-color: blue;
        float: right;
        width: 100px;
        height: 100%;
    }
</style>
Test test test
<div id="test"></div>
<script>
    setInterval(function() {
        document.querySelector('#test').innerText = 'innerText';
    }, 100);
</script>

图像

But replace innerText with textContent and watch it thrash:

图像

Can someone explain this behavior? What can I do to avoid layout thrashing and still change an element's text in a standards-based way?

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.

轮廓

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: 在此处输入图片说明

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