jQuery performance, .css or addClass

纵饮孤独 提交于 2020-01-01 08:03:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!