tags:

views:

1120

answers:

4

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.

+2  A: 

i don't believe jquery does any caching of selectors, instead relying on xpath/javascript underneath to handle that. that being said, there are a number of optimizations you can utilize in your selectors. here are a few articles that cover some basics:

Owen
+4  A: 

I don't think it does (although I don't feel like reading through three and a half thousand lines of JavaScript at the moment to find out for sure).

However, what you're doing does not need multiple selectors - this should work:

$("#navbar .heading:not(:empty)").hide();
Peter Boughton
+6  A: 

jQuery doesn't, but there's the possibility of assigning to variables within your expression and then use re-using those in subsequent expressions. So, cache-ifying your example ...

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

Downside is it makes the code a bit fuglier and difficult to grok.

Neil C. Obremski
+3  A: 

It's not so much a matter of 'does it?', but 'can it?', and no, it can't - you may have added additional matching elements to the DOM since the query was last run. This would make the cached result stale, and jQuery would have no (sensible) way to tell 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 would not be hidden if there was any caching of the query - it would hide only the elements that were revealed earlier.

JoeBloggs
It could detect changes to the dom between calls and invalidate the cache. If that's how it was designed though.
Allain Lalonde
Sounds like more overhead to me - I'd imagine that searching was much more open to shortcuts than monitoring the entire DOM. But who knows? :)
jTresidder
Yeah, agreed, didn't mean a full DOM scan, just meant that if you restricted yourself to changed the DOM using jQuery, you could detect changes.
Allain Lalonde