简体   繁体   中英

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!

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')

It's a good way to do it if you're sure that you're going to access these elements(else it would be wasted resources). Another small thing: it would be best if you access the element in your first example by using myEl and not $(myEl) since $(myEl) has to execute a function(jQuery).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM