Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery / javascript caching elements for efficiency?

Right so I guess the common sense is that for elements you're going to be accessing a lot, the best way is to cache them like so:

var myEl = $('.myclass');

And then you can just access $(myEl) in the future and you don't need to search the DOM again, correct? Ok lets say I have a fairly complex html structure where I need to access several different elements a lot, like 20-30. It's very ugly todo this type of thing 30 times!

var elA = $('.myela'),
    elB = $('.myelb');

Etc etc, you get the idea.. so is there anything "bad" in doing it like this, keep the same class on all those elements, but give them an unique id, then do this:

var myElementObject={};
$('.myelems').each(function(){
     myElementObject[$(this).attr('id')] = $(this);
});

This way it's like I get an object.whateverId and thats the cached element, so now I can use them as I like without re-querying the DOM all the time, is this assumption correct, is this a bad practice? How do you guys go about it?

Thanks!

like image 853
neph Avatar asked Feb 16 '11 01:02

neph


1 Answers

If you're going to assign ids, then just use $('#id') since it uses getElementById which is very fast and probably is not much slower than putting them in some object hash.

Also consider applying a common class to these elements or grouping them in some other way so that you can cache $('.mycommonclass')

like image 75
Vadim Avatar answered Nov 05 '22 19:11

Vadim