Reputation: 445
I read allot of times to avoid global variables and also that local variables are faster. But if i have allot of elements I select by id and need them in allot of functions? Every time the function is executed the DOM is searched again for the elements... Isn't it faster to have the elements cached global?
Upvotes: 0
Views: 45
Reputation: 19487
Or, you could use a single global function to do the lookups, which includes a cache so the dom reading doesn't have to be repeated. Example:
function lookupElementById(id) {
if(lookupElementById.elementCache[id] !== undefined) lookupElementById.elementCache[id] = document.getElementById(id);
return lookupElementById.elementCache[id];
}
lookupElementById.elementCache = {}
Upvotes: 0
Reputation: 437356
It is, but in this situation you should simply find the elements once and then pass the collection as an argument to all the functions that need it.
This way everyone is happy: the DOM is only searched once, and there are still no globals.
Upvotes: 1