I have come across an issue where I have created a grid that gets built up dynamically by using a document fragment and appending elements to it before appending it to a div. I have noticed that appendChild and removeChild seems to be causing memory leaks. I have created a jsfiddle that demonstrates this. I have made sure that all addons for the browsers were disabled (I didn't have much to begin with). If you open developer toolbar (F12) and profile the memory while clicking run, you will notice that the memory will go up. Every time you click it, the memory goes up. It's as if the garbage collection never happens. If there is an issue with the code, please point it out. I have also tried setting the values to the variables as null after they have been appended and have also tried delete, however they don't make a difference.
https://jsfiddle.net/k75ypb76/6
html:
<div id="grid">
</div>
<button id="btnRun">
Run
</button>
CSS:
#grid{
height: 250px;
width: 500px;
overflow: scroll;
border: 1px solid #000000;
}
.row{
border: 1px solid #ff0000;
}
.cell{
display: inline-block;
width: 40px;
background-color: #00ff00;
}
JS:
function run(){
var grid = document.getElementById('grid');
//create the grid 20 times
for(var i =0; i < 20; i++){
var doc = document.createDocumentFragment();
//clear out the grid
while (grid.firstChild) {
grid.removeChild(grid.firstChild);
}
//create 300 rows
for(var x = 0; x < 300; x++){
var row = document.createElement('div');
row.className = 'row';
//create 10 cells per row
for(var y = 0; y < 10; y++){
var cell = document.createElement('div');
cell.className = 'cell';
cell.textContent = x + '-' + y;
row.appendChild(cell);
}
doc.appendChild(row);
}
grid.appendChild(doc);
}
}
var btnRun = document.getElementById('btnRun');
btnRun.addEventListener('click', run);
Thanks, hopefully someone can help out with this issue.