Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is referencing a selector faster in jquery than actually calling the selector? if so, how much does it make a difference?

$(preview-button).click(...)
$(preview-button).slide(...)
$(preview-button).whatever(...)

Is it a better practice to do this:

var preview-button = $(preview-button);
preview-button.click(...);
preview-button.click(...);
preview-button).slide(...);
preview-button.whatever(...);

It probably would be better practice to do this for the sake of keeping code clean and modular, BUT does it make a difference performance wise? Does one take longer to process than the other? Thanks guys.

like image 775
anthonypliu Avatar asked Jan 11 '11 05:01

anthonypliu


2 Answers

Yes it does, when you use the selector without storing it in a variable jQuery needs to parse the DOM EVERY TIME.

If you had something like $(".class") jQuery would need to find the elements with that class every time you use it but if it is stored in a variable it uses the unique identifier in the variable. No need to lookup.

So yeah i would totally recommend storing it into a variable.

UPDATE: Added chaining as an alternative.

If you only use the selector in one place you can also do chaining which means you add one method after another with the same dot notation like this:

$(".class")
       .click(function(){ ... })
       .mouseenter(function(){ ... })
       .css( ... );
like image 159
amosrivera Avatar answered Sep 28 '22 11:09

amosrivera


Yes. You could also chain it:

$(preview-button)
    .click(...)
    .slide(...)
    .whatever(...);
like image 35
Jake Avatar answered Sep 28 '22 10:09

Jake