Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting innerHTML increases HTML nodecount

Explain the problem

So i noticed that on using someElement.innerHTML the DOM Nodes count increases.

enter image description here

I guess that the reference is killed but the memory is still allocated until the garbage collector deletes the object.


Example(HTML):

    <html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="test.css">
        <script src="script.js"></script>
    </head>
    <body onload="startTimer()">
        <div id="timeContainer">Time Goes Here</div>
    </body>

</html>

Example(JavaScript):

 var timer;
 var body;
 var oldTime = "";
 var timeContainer;


 function startTimer(){
    timeContainer = document.getElementById("timeContainer");
    timer = setInterval(getTime, 10);
 }

function getTime(){
    var d = new Date();
    var timeString = d.getUTCHours() +":"+ d.getUTCMinutes(); +":"+ d.getUTCSeconds();

    if(timeString != oldTime){
        oldTime = timeString;
        timeContainer.innerHTML = timeString;
    }
}

What i tried so far

  • I tried to use someElement.textContent.
  • I deleted the whoe ParentElement everytime it refreshes the timer and created a new one

Question

How can i avoid to increase the node count even once when im just refreshing content and why does it need an extra Node anyways?

like image 687
not a number Avatar asked Mar 08 '18 15:03

not a number


People also ask

Why you shouldn't use innerHTML?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.

Is setting innerHTML synchronous?

Setting innerHTML is synchronous, as are most changes you can make to the DOM.

Is innerHTML slow?

innerHTML is slow because it has to look for HTML tags in the value, and parse it into DOM nodes. If you're just inserting plain text that doesn't contain any HTML tags, use textContent instead.

Is innerHTML OK?

innerHTML is very useful and safe when rendering static content (and dynamic content you are completely in control of) to the DOM. However, the security risks associated with . innerHTML occur when this is used when working with user input.


1 Answers

I guess that the reference is killed but the memory is still allocated until the garbage collector deletes the object.

Correct.

How can i avoid to increase the node count even once when im just refreshing content?

You can't, nor should you worry about it. This is the browser's domain, it does what it wants to do when it comes to garbage collection (and different browsers might do it differently).

I deleted the whole ParentElement everytime it refreshes the timer and created a new one

Just because you deleted it (made it inaccessible), doesn't mean it was garbage collected instantly.

like image 198
Adam Avatar answered Sep 29 '22 02:09

Adam