Optimize the JQuery Selectors


Some tips keep in mind when Select element using JQuery Selectors

Selectors Using ElementID

When creating JQuery selector with element Id means, it’s best to start your selector with element ID

Fast:

$("#container div.robotarm");
        This approach is slow because it did not follow Sizzle selector engine, Only ID selections are handle using document.getElementByID()

Super-fast:

$("#container").find("div.robotarm");
        The .find() approach is faster because the selection is handled  using Sizzle selector engine .which is extremely fast because it is native to the browser.

Specificity

                When creating a JQuery selector be more specific on the right-hand side of your selector, and less specific on the left.

Unoptimized:

         $("div.data .gonzalez");

Optimized:

         $(".data td.gonzalez");
         Use <tag>.<class> if possible on your right-most selector, and just tag or just .class on the left.

Avoid the Universal Selector

Selections that specify or imply that a match could be found anywhere can be very slow.
Extremely expensive:
         $(".buttons > *");

Much better:

         $(".buttons").children();

Implied universal selection:

         $(".category :radio");

Same thing, explicit now:

         $(".category *:radio");

Much better:

         $(".category input:radio");

No comments:

Post a Comment