开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜