jQuery - caching multiple selectors to one variabl

2019-08-03 15:10发布

问题:

I need a bit of clarification on jQuery caching. To my understanding, this:

var $element = $('#element');

gives us benefit if we will refer to this element more than once (by refer I mean change it, or listen for an event on it.). Is this correct?

If it is correct, does the following code make any sense, or not, and why?

var $button = $('#submit, #save, #reset');

What I see is that jQuery allows me to do this (hence applying the same nice theme to all 3 buttons), but I cannot find docs anywhere does this help performance in any way.

回答1:

Yes it makes sense, but only if you have to do something more than once with those buttons as a set. It's not probable.

I suggest you don't make too much effort with jquery optimization until you really do things at high frequency (like animations).



回答2:

The performance aspects of this are pretty negligible. You're talking about creating a multiple one element arrays, or one three element array, all of which is pretty negligible.

Basically, jQuery constructs an array of all posible matches for your selectors and returns that.

Worry about other aspects before worrying about the performance of your javascript.



回答3:

The only way it would help performance is if you were going to access $element or $button multiple times. When you do $('#element'), js searches the page for the element with that ID, and does whatever you are telling it to do. The next time you do $('#element'), it seearches the page again for the element. If you use var $element = $('#element'), then the next time you call it (using $element), there is no search, since the reference is already stored.