2

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.