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?