I recently came accross some blog posts about jQuery performance (i.e. http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/) and it was stated in all of them that we should cache the jQuery objects to javascript variables.
What I need to know, though, is if this applies to $(this) as well. Am I going to gain in performance if I do this:
$("#some-link").click("click", function(){
var $this = $(this);
$this.doSomeThing();
});
Thank you in advance for your help.
this
may refer to many different objects.
Caching $(this)
may not be important, because this
is already the current element and thus jQuery does not need to search the DOM for this element.
However in a single function if you have more than one times calling $(this)
, it is wise to put $(this)
to a variable instead of calling $(this)
many times.
$("#some-link").click("click", function(){
var $this = $(this);
$this.doSomeThing();
$this.doThisThing();
$this.doThatThing();
});
would be more efficient than
$("#some-link").click("click", function(){
$(this).doSomeThing();
$(this).doThisThing();
$(this).doThatThing();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With