• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

155
Views
How to create DOM elements in JS memory-efficiently?

Consider the following code that inserts 100,000 spans with the content '0' inside.

<body>
    <script type="module">
        const container = document.getElementById('root')
        const CHILDREN_COUNT = 100000;

        for (let i = 0; i < CHILDREN_COUNT; i++) {
            const newChild = document.createElement("span");
            newChild.innerHTML = '0'
            container.appendChild(newChild)
        }
    </script>

    <div id="root" style="overflow-wrap: break-word">
    </div>
</body>

In my mind, after each loop, the garbage collection should clean up newChild as there are no further references to this var. The container itself I assume is a pointer to the DOM element, instead of being the entire thing in memory, and either way, should be cleaned after the loop executes.

However, testing reveals this page will take up 200,000kb~ of memory (per task manager in Chromium), but if CHILDREN_COUNT is reduced to 10, it takes up only c. 30,000kb~ of memory. Could the difference be entirely down to the DOM having to hold more span elements? Since the content for each span is minimal, I would have assumed not.

Is there something that I could do here to better manage memory use?

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

check DocumentFragment -> https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment

 var list = document.querySelector('#list')
const CHILDREN_COUNT = 100000;
var fragment = new DocumentFragment();

        for (let i = 0; i < CHILDREN_COUNT; i++) {
          var spanEl = document.createElement('span');
          spanEl.innerHTML ='0';
          fragment.appendChild(spanEl);
        }
 
list.appendChild(fragment);

enter image description here

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error