I am writing a jQuery plugin and I am at the optimization stage.
I wonder which of these leads to a quicker script in general, and what sort of mitigating factors are important:
- Have the script generate lots of classes and ids at the start so finding elements in the dom is easier (quicker too?) later on.
- Keep classes and ids to a minimum (so save time by not creating them), but then look for elements in more convoluted ways later (eg the nth item in an object), which I presume is slower than getting by id/class.
The question is not really specific enough so I can give you advice directly relevant to your code, but here are some of my favorite jQuery optimization tips:
#containerdiv, then do$(something, '#container');.myclassis slow. Internally, jQuery has to go through every single element to see if it has the class you are searching for, at least for those browsers not supportinggetElementsByClassName. If you know that a class will only be applied to a certain element, it is way faster to dotag.myclass, as jQuery can then use the nativegetElementsByTagNameand only search through those.$('#myform input:eq(2)');or something like that, I prefer to do$('input','#myform').eq(2);to help jQuery out.