为什么设置textContent导致布局颠簸? [英] Why does setting textContent cause layout thrashing?
问题描述
必须说明:
textContent在DOM级别3中引入的DOMString类型
该属性返回此节点及其后代的文本内容。当它被定义为空时,设置它不起作用。 在设置时,可以删除此节点可能拥有的任何可能的子节点,并且如果新字符串不为空或为空,则将其替换为包含此属性设置为的字符串的单个Text节点。
修正
非颠簸的方法是获取元素的文本节点和修改那些而不是使用 textContent
或 innerText
(这是非标准的)。
var test = document.getElementById(test);
var a = document.createTextNode();
test.appendChild(a);
setInterval(function(){
a.nodeValue =Test test test;
},100);
这里是一个工作小提琴
当然,如果实际的文字会发生变化,就会出现一个画面来更新你所看到的内容。
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.
这篇关于为什么设置textContent导致布局颠簸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!