0

I wonder if selector "$cacheA" will be cached on page load in the example below?

// MY JQUERY FUNCTION/PLUGIN
(function( $ ){
$.fn.myFunction = function() {

var $cacheA = this,
$cacheB = $cacheA.children(),
$cacheC = $cacheB.eq(0);
$cacheD = $cacheA.parent();    

$cacheD.click(function(){

$cacheA.toggle();
$cacheB.fadeIn();
$cacheC.slideUp();

});

};
})( jQuery );
// END JQUERY FUNCTION/PLUGIN



$(window).load(function(){

$('#mySelector').myFunction();

});

Would it be any reason to do this:

$(window).load(function(){

var $mySelector = $('#mySelector');

$mySelector.myFunction();

});
3
  • If $cacheA is cached I assume that $cacheB, $cacheC and $cacheD will also be cached at page load? Commented Apr 16, 2011 at 13:41
  • This question makes no sense. What do you mean, "cached"? Commented Apr 16, 2011 at 13:46
  • With "cache" I mean: By saving the selector in a variable the browser only have to do doom travel once. This will speed up the script if the selector is useed multiple times. Commented Apr 16, 2011 at 14:02

2 Answers 2

2

If, inside your "load" handler, you were to do many jQuery operations with "$mySelector", then saving that in a variable would be a good idea. However, in your example, you only use the value once, so it really makes no difference at all.

Sign up to request clarification or add additional context in comments.

3 Comments

Thansk for your answer. The $mySelector will be used in the jquery function. See "var $cacheA = this". Will it make any difference then?
+1 Caching is only valuable when you're traversing the DOM over and over again with the same selector.
No - if you save the $('#something') value, then you can re-use it many times. Inside your jQuery plugin "myFunction", it will be the value of this. However, the variables "$cacheB", "$cacheC", and so on, are all local variables, and they will be re-computed every time you call "myFunction", even if you call it with the same starting jQuery object ("$mySelector").
0

Firstable, $cacheA and others inside click function will be undefined.

$cacheD.click(function(){

$cacheA.toggle();
$cacheB.fadeIn();
$cacheC.slideUp();

});

Second,

$.fn.myFunction = function() {

var $cacheA = this,
$cacheB = $cacheA.children(),
$cacheC = $cacheB.eq(0);
$cacheD = $cacheA.parent();
}

So, after $('selector').myFunction() how can I use $cacheB, $cacheC and $cacheD? Where they are will store?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.