Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery performance, .css or addClass

I have a big jQuery code and I am thinking at speed performance of my functions. When an element is clicked (mousedown) i need to assign an image as background. I can do this by 2 ways:

$('#element li.class').css({"background":"someimageURL"});

or

$('#element li.class').addClass("someclass");

where "someclass" have the actual CSS background image. Witch function works better in this case.

Is there a way to test various functions speed?

Thank you

like image 201
Mircea Avatar asked Feb 25 '10 18:02

Mircea


2 Answers

I'm almost certain .addClass() would be the faster of the two. This involves essentially tacking on another classname to the element, whereas the alternative would require iterating through the elements styles and setting many explicit rules.

Setting a couple css rules via $.css() is likely nothing to worry about, but if you find yourself setting many, often, it's time to create a class and apply/remove that as needed.

I've extracted the logic of both methods into a single location for you to review if you like.

http://pastie.org/842738

like image 188
Sampson Avatar answered Oct 14 '22 01:10

Sampson


Add class is absolutely faster, see this performance test of $.addClass() vs $.css() vs $.removeClass().addClass() vs plain js - http://jsperf.com/jquery-css-vs-addclass-speed/2

like image 44
Justin McCammon Avatar answered Oct 14 '22 02:10

Justin McCammon