Is jQuery any sort of "selector" caching?

For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if DOM changes have not 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 as a nontrivial blow.

+49
jquery jquery-selectors
Nov 15 '08 at 0:13
source share
14 answers

There is no jQuery, but it is possible to assign variables in your expression and then reuse these in subsequent expressions. So, caching your example ...

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

Downside makes the code a little more complicated and complicated.

+14
Nov 15 '08 at 0:57
source share

Always cache your choice!

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

Or almost always ... Usually, you should store a cached copy of the jQuery object in a local variable, unless you expect it to change or you need it only once.

 var element = $("#someid"); element.click( function() { // no need to re-select #someid since we cached it element.hide(); }); 
+23
Apr 15 '12 at 4:15
source share

This is not so much a question โ€œisn't it?โ€, But โ€œcan it?โ€ And no, it's not possible - you could add additional comparable elements to the DOM since the last request. This would make the cached result obsolete, and jQuery would have no (sensible) way of saying other than running the query again.

For example:

 $('#someid .someclass').show(); $('#someid').append('<div class="someclass">New!</div>'); $('#someid .someclass').hide(); 

In this example, the newly added element will not be hidden if there is any caching of the request - it will hide only those elements that were discovered earlier.

+13
Nov 16 '08 at 11:26
source share

I just made a method to solve this problem:

 var cache = {}; function $$(s) { if (cache.hasOwnProperty(s)) { return $(cache[s]); } var e = $(s); if(e.length > 0) { return $(cache[s] = e); } } 

And it works as follows:

 $$('div').each(function(){ ... }); 

The results are accurate, as far as I can tell from this simple check:

 console.log($$('#forms .col.r')[0] === $('#forms .col.r')[0]); 

NB, it will violate your implementation of MooTools or any other library that uses the $$ notation.

+12
Oct 14 '11 at 13:24
source share

I donโ€™t think it is (although I donโ€™t want to read through three and a half thousand lines of JavaScript at the moment to find out for sure).

However, what you do does not require multiple selectors - this should work:

 $("#navbar .heading:not(:empty)").hide(); 
+8
Nov 15 '08 at 0:25
source share

Like your $$ approach, I created a function (with the same name) that uses a remembering pattern to store a global cleaner and also takes into account the second context parameter ... for example $$ (". Class", "#context"). This is necessary if you use the find () chain that appears after $$ is returned; therefore, it will not be cached alone unless you first cache the context object. I also added a boolean parameter at the end (2nd or 3rd parameter depending on the context used) to make it return to the DOM.

the code:

 function $$(a, b, c){ var key; if(c){ key = a + "," + b; if(!this.hasOwnProperty(key) || c){ this[key] = $(a, b); } } else if(b){ if(typeof b == "boolean"){ key = a; if(!this.hasOwnProperty(key) || b){ this[key] = $(a); } } else{ key = a + "," + b; this[key] = $(a, b); } } else{ key = a; if(!this.hasOwnProperty(key)){ this[key] = $(a); } } return this[key]; } 

Using:

 <div class="test">a</div> <div id="container"> <div class="test">b</div> </div>โ€‹ <script> $$(".test").append("1"); //default behavior $$(".test", "#container").append("2"); //contextual $$(".test", "#container").append("3"); //uses cache $$(".test", "#container", true).append("4"); //forces back to the domeโ€‹ </script> 
+6
Jul 20 '12 at 17:10
source share

I don't believe jquery caches selectors, instead relying on xpath / javascript under it. that, as they say, there are a number of optimizations that you can use in your selectors. Here are a few articles that cover some of the basics:

+4
Nov 15 '08 at 0:23
source share

This $$ () works fine - should return a valid jQuery object in any case never undefined.

Be careful! It should / cannot with selectors that can dynamically change, for example. by adding nodes matching the selector, or using pseudo-classes.

 function $$(selector) { return cache.hasOwnProperty(selector) ? cache[selector] : cache[selector] = $(selector); }; 

And $$ can be any funciton name, of course.

+3
Aug 23 '12 at 14:00
source share

John Resig, in an interview with jQuery Internals at jQuery Camp 2008, mentions some browsers that support events that fire when the DOM changes. For such cases, Selctor results can be cached.

+2
Mar 20 '11 at 10:12
source share

There is a good plugin called jQache that does just that. After installing the plugin, I usually do this:

var $$ = $ .q;

And then just

$$ ("# navbar.heading"). hide ();

The best part of all this is that you can also clear your cache if necessary if you are doing dynamic things, for example:

$$ ("# navbar.heading", true) .hide (); // flushes the cache and hides the new (just found) # navbar.heading

AND

$$ clear () .// Completely clears the cache

+2
Oct 30 '14 at 10:57
source share

jQuery Sizzle automatically caches the latest functions created from selectors to find DOM elements. However, the elements themselves are not cached.

In addition, Sizzle maintains a cache of the most recently compiled features. The cache has a maximum size (which can be changed, but has a default value), so you do not get errors from memory when using many different selectors.

+1
Dec 03 '12 at 23:14
source share

jsPerf does not work today, but this article assumes that the performance gained from caching jQuery selectors will be minimal.

enter image description here

It could just be browser caching. A valid selector was only one identifier. Additional tests should be performed for more complex selectors and various page structures ...

+1
Jul 02 '15 at 9:16
source share

$. selectorCache () is useful:

https://gist.github.com/jduhls/ceb7c5fdf2ae1fd2d613e1bab160e296

Gist insert:

 <script src="https://gist.github.com/jduhls/ceb7c5fdf2ae1fd2d613e1bab160e296.js"></script> 
+1
May 24 '16 at 17:25
source share

Check if this helps https://plugins.jquery.com/cache/

Crossed this as part of our regular project

0
May 25 '15 at 5:47
source share



All Articles