carpat
carpat

Reputation: 871

JQuery caching selectors - am I misunderstanding?

I'm working on some JQuery code and I have a question about caching selectors. I have a certain function that is called when scrolling (and thus needs to be fast). I tried caching the selectors used in the function during the initialization, like so:

var myElement = $('#myElement');

function onScroll()
{
    myElement.whatever();
}

When I profile the code in firebug, I see that the JQuery selector function gets called exactly 5 times as often as the onScroll function (I use 5 different selectors in the function), and is responsible for the majority of execution time.

1) So what exactly is the benefit of caching this way? I'm not being sardonic :)

2) I understand that the selector needs to be re-run in case the DOM changes, but is there any way to cache a single selected object so that the function doesn't need to run each time, while staying within JQuery?

Upvotes: 1

Views: 376

Answers (1)

Guffa
Guffa

Reputation: 700422

  1. When you are using the variable myElement you are using a jQuery object that contains references to the elements that were found when you created the object. The selector is not rerun to update the set of elements when you use the jQuery object.

  2. Yes, you do exactly as you have shown.

Upvotes: 2

Related Questions