Getting real width with $ (this) .scrollWidth is really slow

I'm doing a parry

$('.Row .Cell .Text').each(function (index, item) { if (this.scrollWidth > $(this).parent().width()) $(this).next().show(); else $(this).next().hide(); }); 

everything is fine when I have no allocation of $ ('. Row.Cell.Text'). but if I have a selection of rows and cells, the code above and in particular

 this.scrollWidth 

takes time allocation.

Any idea how I can get the same, but faster?

added jsFiddle fiddle

+4
source share
3 answers

I assume that you are trying to hide .Icon from .Text width> .Cell . See below approach,

I tried moving jQuery code out of the side loop using filter .

CSS

 /*set overflow for .Text - This lets you calculate the actual width of .Text*/ .Text { overflow: hidden; } /* Hide .Icon by default and show only if .Text width < .Cell width*/ .Cell .Icon { display: none; } 

Js

 $('.Row .Cell .Text').filter(function (i, el) { return el.scrollWidth <= this.parentNode.scrollWidth; //Thanks @nicoabie }).next().show(); 

DEMO: http://jsfiddle.net/nYSDy/4/

+1
source

It seems that the bulk of the performance hit actually comes from this:

$ (this) .next () hide () ;.

At first, I thought you might get a performance hit because of how jquery can handle additional text nodes created by spaces between your elements, so I tried:

this.nextSibling.nextSibling.style.display = 'none';

It really didn't help, so it seems that just setting the style on this set of elements is extremely slow. To get around this, you might consider setting a default style for what you expect from the most common case, and then only react to another case. For the example script you posted, this will result in:

CSS

 .Icons { display: none; } 

New JS:

 $('.Row .Cell .Text').each(function (index, item) { if (this.scrollWidth > $(this).parent().width()) $(this).next().show(); }); 

Appendix: it turns out that adding a class to all of these elements is a little faster, so you can do this http://jsfiddle.net/XuhaT/1/ :

CSS

 #vTable { width:800px; } .Icon { display: none; } .visible.Icon { display: block; } 

JS:

 $("#countOfItems").html($('#vTable .Row ').length); var startDate = new Date(); $('.Row .Cell .Text ').each(function (index, item) { if (this.scrollWidth > $(this).parent().width()) $(this).next().addClass('visible'); }); var endDate = new Date(); $("#claculationTime").html(endDate - startDate); 
+2
source

You can speed Brandon's response about 6 times using this comparator

 if (this.scrollWidth > this.parentNode.scrollWidth) 

Hope this helps!

+1
source

All Articles