2

I'm trying to get my head around - why is the DOM Nodes keeps on going up when I'm checking my website in the Performance Monitor.

I've added this simple code that just looping on:

1) adding and element to a wrap, 2) bind it with a click event. 3) removing it.

but still the DOM Nodes are always up the I check the performance. any thoughts?

image showing the issue and the monitor

<!DOCTYPE html>
<html>
<head>
    

    <title></title>
    <style>
        .wrap{
            font-size:50px;
        }
    </style>
</head>
<body >
    <div class="wrap">
        <div></div>
    </div>
    

   <script>
       var counter = 0;

       setInterval(function () {

           //increase counter (for display) 
           counter++;

           //get wrap 
           var wrap = document.getElementsByClassName("wrap")[0];

           //remove its children
           while (wrap.firstChild) {
               wrap.firstChild.removeEventListener("click", onclick);

               wrap.removeChild(wrap.firstChild);
           }

           //create new element 
           var div = document.createElement("div");        // create a div element
           div.innerHTML = 'hello mosh (' + counter + ')';
           
           //bind events
           div.addEventListener("click", onclick);

           // append the div to wrap
           wrap.appendChild(div);                                



       }, 200);

       //on click function
       var onclick = function () { alert('click'); }

   </script>
</body>
</html>
Roey Zada
  • 663
  • 10
  • 30

1 Answers1

2

The v8 engine is garbage-collected, removed DOM elements are not destroyed immediately. Occasionally unused (unreachable) objects are garbage-collected.

If I wait long enough, with your code, I do see DOM Nodes go back down to the original value (had to bump the interval to 20 to speed up the process).

v8 gc

For this reason it is often more efficient to not remove DOM elements, and instead just replace the HTML content.

<!DOCTYPE html>
<html>
<head>
    

    <title></title>
    <style>
        .wrap2 {
            font-size:50px;
        }
    </style>
</head>
<body >
    <div class="wrap2">
        <div></div>
    </div>
    

   <script>
       var counter = 0;
       var wrap = document.getElementsByClassName("wrap2")[0];
       var div = wrap.getElementsByTagName("div")[0];

       setInterval(function () {

           counter++;

           div.innerText = 'hello mosh (' + counter + ')';
           
       }, 20);

       //on click function
       var onclick = function () { alert('click'); }

   </script>
</body>
</html>

v8 gc

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • This was very informative. Managed to get an insane decrease in the amount of DOM nodes being created every second (from 700 to 16!) within a matter of minutes thanks to this simple advice. Thank you. – Dylan Jan 30 '23 at 02:03