jQuery width() method performance

后端 未结 3 752
一个人的身影
一个人的身影 2020-12-21 17:09

I\'m a jQuery noob trying to track down a performance issue that we\'re having with large tables. We have a homegrown table widget which, among other things, sets the colum

相关标签:
3条回答
  • 2020-12-21 17:25

    As I know - .width() is taking real width(not always one set in css) and to get it - browser must calculate it (forced page redraw and width calculation itself). Now, you are setting width, browser need to redraw everything. It may do that with slight delay, but in next step you are taking width again - browser MUST redraw page to get a real width. Count widths first, than - in another loop, set calculated values. I think this should help

    EDIT:

    Tested this comparing to Kelvin B approach. Difference is not significant. Looks like the best is when css("width") is used. Here are tests: Hm. Tested this. Comparing with approach I suggested. Appeared that difference is not big. Here are test: width one loop, css width one loop, css two loops, width two loops. In result - almost no difference. The slowest - "width one loop". Fastest - one of those with css. Different from time to time for me.

    Note: four different tests with on case because looks like js perf does not clear html state between test cases.

    Not sure what could be done in your case, but what I see strange is .width('1%') you are using. For me it looks like you do not need it, so maybe you can try removing it.

    0 讨论(0)
  • 2020-12-21 17:35

    Use .css("width") instead of .width(), changes were made to the .width() method that make it perform slower. Read this for more information: http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/

    var commonWidth = Math.max(
      Math.min(parseFloat(headerTd.css("width")), 100),
      dataTd.width()
    );
    
    0 讨论(0)
  • 2020-12-21 17:47

    if you do .width (and also .css("width")) on table cell (or headers) of very large tables, it takes an awful lot of time FOR HIDDEN ELEMENTS !!!, and is very fast for visible elements. The reason is, if the element is hidden, the browser, being nice and efficient, has not made any effort to find out what the width would be, if the element were visible. But jQuery's .width, apparently, for hidden elements, returns what the width would be, if it were visible, instead of just returning zero (it's hidden alright). For large tables, that means that the browser has to render the whole table again. If the table is really large it can take over a second. And if you then do that for multiple hidden columns (just measuring their widths) your page becomes useless.

    so do not measure width of hidden elements unless you REALLY need to know.

    relevant link, repeating what I just said (and more): here

    0 讨论(0)
提交回复
热议问题