Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce the amount of DOM redraws while resizing table?

I have a table with resizing functionality. Actually, it is not a <table> element. I use the cluster of <div> elements. Briefly, my resizing function is a nested 'for' loops. It is something like this:

function resizeTable (computedCellWidth) {
    for (var r = 0; r < rows.length; r++) {
        for (var c = 0; c < rows[r].cells.length; c++) {
            rows[r].cells[c].domNode.style.width = computedCellWidth + 'px';
        }
    }
}

As I understand, each rows[r].cells[c].domNode.style.width = computedCellWidth + 'px'; causes the full document redraw. So, if a table is large enough, then table resizing extremely slows down the browser.

I tried to use throttling (100 ms) to reduce the amount of resize events, but if a table is large enough, then even a single resizing takes too much time.

Can I assign all width properties first, and only after that launch the single redraw?

like image 798
splash27 Avatar asked Sep 23 '15 10:09

splash27


1 Answers

Give width in percent despite pixels in order to achieve responsive layouts. If percent can't be used for any reason then DocumentFragment is the best bet in this case. It is intended for the temporary storage of the DOM structures. It won't calls the rendering engine of the browser until the modified fragment is inserted back to the document.

This is how a portion of the document would be fragmented.

var elem = document.getElementById("resizableTable");//assumes resizableTable is the id of the element has to modify
var frag = document.createDocumentFragment(); //method creates an imaginary node object with all properties.
frag.appendChild(elem);

Now iterate through the fragment to make the changes and then insert back the frag. This won't redraw the doc each time when you change something in the fragment.

PS: I know, I am late. But, thought this could help someone who need to do the same.

like image 161
Moorthy Avatar answered Oct 20 '22 07:10

Moorthy