Reputation: 2852
I've accidentally found that if I alter a node's innerText
(or innerHTML
) with JavaScript, the number of garbage DOM nodes increases. Accordingly, if I force the Garbage Collector to execute, the number of DOM nodes drops.
To illustrate the problem, paste the following code snippet inside a HTML file:
<span></span>
<script>
const spanNode = document.getElementsByTagName('span')[0];
setInterval(() => {
spanNode.innerText = (new Date()).toUTCString();
}, 1000);
</script>
Then, open the file in Chrome
or Edge
(I checked these only two browsers) and then open the Developer Tools:
Notice how the number of DOM Nodes
increases by one every single second.
Now if you hit the bin button (besides the "Memory" checkbox) to force the Garbage Collector to execute, the number of DOM Nodes
drops. This might imply that altering innerText
effectively creates a new node.
Can anybody shed a light here?
Upvotes: 1
Views: 312
Reputation: 2628
According to the HTML Standard (https://html.spec.whatwg.org/multipage/dom.html#the-innertext-idl-attribute), the second setter
step involves the creation of a new DocumentFragment
, which will replace the current content. The way I understand it, this ensures that everything inside the new element follows the specification (for instance, CR
s are translated into br
s). I would also expect this to be important for security, as you cannot mess with the DOM itself from your text.
Of course, the DOM specification does not say what the browser should do with the memory representation of the old node. However, the behavior you are describing is exactly what you would expect from a garbage collector. Instead of getting rid of the object, it gets queued for removal in the future. In fact, your experiment shows that no memory leak has happened and every object is removed when garbage is collected.
Upvotes: 1