Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are extra $(...) calls bad?

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);
    });
});
like image 668
Adam Rackis Avatar asked Dec 06 '11 01:12

Adam Rackis


2 Answers

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);
    });
});
like image 95
Shad Avatar answered Sep 23 '22 21:09

Shad


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.

like image 20
PeeHaa Avatar answered Sep 24 '22 21:09

PeeHaa