Why does setting textContent cause layout thrashing?

后端 未结 2 881
忘掉有多难
忘掉有多难 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:00

    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.

    profile

提交回复
热议问题