问题
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
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/2336509/jquery-performance-css-or-addclass