$(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.
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( ... );
Yes. You could also chain it:
$(preview-button)
.click(...)
.slide(...)
.whatever(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With