Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery do any kind of caching of "selectors"?

For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?

if ($("#navbar .heading").text() > "") {   $("#navbar .heading").hide(); } 

and

var $heading = $("#navbar .heading");  if ($heading.text() > "") {   $heading.hide(); } 

If the selector is more complex I can imagine it's a non-trivial hit.

like image 693
Allain Lalonde Avatar asked Nov 15 '08 00:11

Allain Lalonde


People also ask

Does jQuery cache selector?

Caching enhances the performance of the application. Cache your jQuery selectors for better performance. This can be done using the ID as your selector. For example, this caches the selector and stores it in variable.

Which selector is faster in jQuery?

ID and Element selector are the fastest selectors in jQuery.


1 Answers

Always cache your selections!

It is wasteful to constantly call $( selector ) over and over again with the same selector.

Or almost always... You should generally keep a cached copy of the jQuery object in a local variable, unless you expect it to have changed or you only need it once.

var element = $("#someid");  element.click( function() {    // no need to re-select #someid since we cached it   element.hide();  }); 
like image 172
gnarf Avatar answered Sep 24 '22 23:09

gnarf