Reputation: 1031
I use this simple function to cache my selectors:
var selector_cache = function(){
var collection = {};
function get_from_cache( selector ) {
if (undefined === collection[selector]) {
collection[selector] = $(selector);
}
return collection[selector];
}
return { get: get_from_cache };
};
To get my cached selectors I do the following:
window.selectors = new selector_cache();
var $selectors = window.selectors;
var $program_home = $selectors.get('section#program_home');
My question is: Doing $program_home.find('.home_section');
jQuery is going to traverse the DOM again? Or does it get the children of the selector from the cached version?
I would like to avoid to traverse the DOM again, so if jQuery traverses the DOM again, maybe the best solution is to cache the children as well (?) like this: $selectors.get('section#program_home .home_section');
Thanks for any suggestion!
Upvotes: 0
Views: 97
Reputation: 339856
Your $selectors
variable is a jQuery object, and you've explicitly invoked a method on that object (.find
) so yes, it will traverse the DOM again (albeit only looking at descendants of that node, not the entire DOM).
Upvotes: 1
Reputation: 700432
"Doing $program_home.find('.home_section'); jQuery is going to traverse the DOM again? Or does it get the children of the selector from the cached version?"
Well, neither.
The $program_home
variable contains a jQuery object that contains references to the elements that were found earlier using the section#program_home
selector.
The find
method won't search the entire DOM, it will only search inside those elements. If there are currently other elements that would also match the original selector, those are not included.
The selector cache is not involved at all in this operation.
Upvotes: 3