If I have code that pulls down a jQuery object, and then makes some further calls on it
$("a.postSyncLink").click(function () {
var resultsTarget = $("span", $(link).parent().next());
resultsTarget.html("<img style='position: absolute;' src='" + waitImgUrl + "'/><span>Sync in progress</span>");
$.get($(this).attr("data-url"), function (returnVal) {
resultsTarget.text(returnVal);
});
});
Is it considered bad practice to subsequently (and unnecessarily) wrap that object in the jQuery function? Does jQuery optimize superfluous calls like this?
$("a.postSyncLink").click(function () {
var resultsTarget = $("span", $(link).parent().next());
$(resultsTarget).html("<img style='position: absolute;' src='" + waitImgUrl + "'/><span>Sync in progress</span>");
$.get($(this).attr("data-url"), function (returnVal) {
$(resultsTarget).text(returnVal);
});
});
If they aren't being used to clone the original jQuery object, then yes it's bad:
http://api.jquery.com/jQuery/#cloning-jquery-objects
A jQuery object passed to jQuery
is cloned, which is processor time I would not waste.
When storing a reference to a jQuery object I find it useful to prefix the variable name with a $
, this helps me remember that it is a jQuery object, and doesn't need to be re-wrapped:
$("a.postSyncLink").click(function () {
var $resultsTarget = $("span", $(link).parent().next());
$resultsTarget.html("<img style='position: absolute;' src='" + waitImgUrl + "'/><span>Sync in progress</span>");
$.get($(this).attr("data-url"), function (returnVal) {
$resultsTarget.text(returnVal);
});
});
It hurts performance since you are creating new jquery objects every time you do it.
Avoid it when possible.
Just create the jquery object and use that.
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