I have a big jQuery code and I am thinking at speed performance of my functions. When an e开发者_如何学Clement 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
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
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
精彩评论