Can't Tell
Can't Tell

Reputation: 13426

How can I optimize the following JavaScript which sets the CSS properties of Elements

I have a page with JavaScript which takes a very long time to run. I have profiled the code using Firefox and following is the output.

enter image description here

As you can see I have moved the time consuming lines to a method _doStuff, which seems to do a lot of Graphic related things. Following is the content of the _doStuff method.

  _doStuff:function(tds,colHeaderTds,mainAreaTds ){
       for (i = 1; i < tds.length; i++) {
            if (colHeaderTds[i].offsetWidth <= tds[i].offsetWidth) {
              colHeaderTds[i].style.width = tds[i].offsetWidth + "px";
            }
            mainAreaTds[i].style.width = colHeaderTds[i].offsetWidth + "px";
          }

  },

I am assuming that the time consuming Graphics sections are due to setting the widths of the elements. Is this observation correct? And how should I go about optimizing the code so that it would take less time to load the page?

Upvotes: 2

Views: 38

Answers (1)

Sergei Panfilov
Sergei Panfilov

Reputation: 1221

Every iteration of your loop JS changes your DOM tree and forces browser to repaint it.

The good practice is to make a copy of your element, modify it in the loop, and after loop change the .innerHTML of the former element.

More reading about repaints on the topic here

Upvotes: 1

Related Questions