Best Practices

Write jQuery that stays fast and readable.

A few habits keep jQuery code healthy:

  • Cache selections in a variable instead of re-querying the DOM.
  • Chain methods on the same set to avoid repeat lookups.
  • Delegate events for dynamic content.
  • Prefix cached jQuery variables with $ by convention: var $list = $("#list");.
// Slower: selects #list three times
$("#list").addClass("on");
$("#list").show();

// Better: select once, cache, chain
var $list = $("#list");
$list.addClass("on").show();

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A performance-sensitive page caches the $('#nav') result in a variable to avoid re-querying the DOM on every scroll event.
  • A plugin author prefixes all event names with a namespace (.myPlugin) so they can be removed cleanly without touching other handlers.
  • A team standard requires all jQuery selectors to start from a cached parent element to limit the DOM traversal scope.

More examples

Cache jQuery selections in variables

Storing the selection in $list and $items avoids re-running the CSS selector engine on each click.

Example · html
<ul id="list">
  <li>One</li><li>Two</li><li>Three</li>
</ul>
<button id="run">Process</button>
<script>
$(function () {
  var $list = $("#list");   // cached once
  var $items = $list.find("li");
  $("#run").click(function () {
    $items.each(function () {
      $(this).text($(this).text().toUpperCase());
    });
  });
});
</script>

Use event delegation over per-element binding

A single delegated handler on the parent covers future items automatically and uses far less memory than per-item binding.

Example · html
<ul id="feed"></ul>
<button id="add">Add item</button>
<script>
$(function () {
  // Good: one delegated handler
  $("#feed").on("click", "li", function () {
    $(this).toggleClass("done");
  });
  var n = 0;
  $("#add").click(function () {
    n++;
    $("#feed").append("<li>Item " + n + "</li>");
  });
});
</script>

Namespace events for clean teardown

Naming events with a .namespace lets you remove all of a component's listeners in one .off() call without knowing their exact types.

Example · html
<div id="widget">Widget area</div>
<button id="init">Init widget</button>
<button id="destroy">Destroy widget</button>
<script>
$(function () {
  $("#init").click(function () {
    $("#widget").on("click.myWidget mouseenter.myWidget", function (e) {
      console.log("Widget event:", e.type);
    });
  });
  $("#destroy").click(function () {
    $("#widget").off(".myWidget"); // removes all myWidget handlers at once
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.