Reputation: 1513
When writing jQuery
, what leads to better performance?
Reference items directly via their id/class
each time i.e
$('#myDiv')
Save useful jQuery
selectors as variables and reuse these i.e var
myDiv = $('#myDiv')
Traverse the tree from a specific point using prev() next()
find() closest()
etc
Upvotes: 0
Views: 31
Reputation: 1114
It really depends on the situation, but as you state, it is (usually) a good idea to 'cache' your selectors. There's also a lot of behind-the-scenes mechanics, that could help you out - Such as using $("#id").find(".subchild")
instead of $("#id .subchild")
, since using only a id selector, uses the browsers internal 'find-element-with-this-id' engine.
Have a look at https://learn.jquery.com/performance/optimize-selectors/ - It really explains a lot on how to speed up some things :)
Upvotes: 1
Reputation: 20633
If you plan on reusing a selector multiple times then it's a good idea to cache them in a variable to avoid expensive DOM lookup each time.
Upvotes: 0