Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to jQuery cache $(this)?

Tags:

jquery

I'm still learning about jQuery, but I have not been able to find a solid answer. I know every time you use the jQuery selector $(...) there is a performance cost, but does $(this) have a significant cost where you should cache it before using it a lot?

var $this = $(this);
like image 559
Jason More Avatar asked Oct 04 '10 16:10

Jason More


People also ask

Should I cache jQuery?

In case you are not adding or removing DOM elements, you should always cache the results of your jQuery selectors.

Does jQuery cache selector?

jQuery Sizzle does automatically cache the recent functions that have been created from the selectors in order to find DOM elements. However the elements themselves are not cached.


1 Answers

If you're using it a lot, yes it makes sense, or chain, e.g.:

$(this).fadeIn().fadeOut().somethingElse();

If it expensive? No not really in the grand scheme of things...but if you're in a loop the cost multiplies so it's best to cache it. If you're using it more than once it makes sense, how much sense depends on how much performance matters for that bit of code I suppose.

like image 156
Nick Craver Avatar answered Sep 28 '22 08:09

Nick Craver