Slow response when the HTML table is big

前端 未结 6 1957
情深已故
情深已故 2020-12-14 17:29

I am using JavaScript to generate a HTML table of 4 columns, but when the table became very large (e.g. more than 1000 rows), the user could face lag between their interacti

6条回答
  •  一个人的身影
    2020-12-14 17:58

    The first thing that is slowing your loop down is .insertRow(). You're doing this at the top of your loop and then adding cells to it. After the row is added, and after each cell is added, the browser is doing layout calculations. Instead use .createElement() and then .appendChild() at the end of your loop.

    Demo: http://jsfiddle.net/ThinkingStiff/gyaGk/

    Replace:

    row = tableContent.insertRow(i);
    

    With:

    row = document.createElement('tr');
    

    And add this at the end of your loop:

    tableContent.tBodies[0].appendChild(row);
    

    That will solve your loading speed issue. As for the hover, you have way too many CSS rules affecting your tr and td elements using tag selectors. I removed a few, and used classes on a few, and the hover highlighting is much faster. Specifically, I noticed that overflow: hidden on the td elements slowed it down considerably. Consider combining some of your rules, using simpler selectors, and adding classes to elements for quicker CSS processing. During hover many things have to be recalculated by the the layout engine, and the fewer CSS rules the better. One example I saw in your code was #tables tbody tr when there was only one tbody in the table. #tables tr would have sufficed. Better than either of those is a class. I used .row in my demo.

    Best practices from Google Page Speed:

    • Avoid descendant selectors: table tbody tr td
    • Avoid redundant ancestors: body section article (body never needed)
    • Avoid universal (*) selectors: body *
    • Avoid tag selectors as the key (right-most): ul li
    • Avoid child or adjacent selectors: ul > li > a
    • Avoid overly qualified selectors: form#UserLogin (# is already specific)
    • Make your rules as specific as possible (class or id).

提交回复
热议问题