Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 56 ยท Migration and Performance

Best Practices, Performance and Pitfalls

Write fast, safe jQuery: cache selections, batch DOM changes, use delegation, clean up with .off(), avoid XSS with .text() and escape selectors from user input.

jQuery makes the DOM easy to change, and that ease hides costs. A line like $(".row").addClass("x") looks free, yet it searches the page, wraps the result and touches every match. Most slow or fragile jQuery pages are not wrong in any single line; they repeat small costs thousands of times, forget to clean up, or trust text that should have been treated as data.

This lesson collects the habits that separate a tidy jQuery codebase from a fragile one: caching, batching DOM writes, delegation, cleanup, readable chains, debugging checks and, most important of all, safe handling of untrusted input. Measure before you optimize: on a small page none of the performance advice matters, but the security advice always does.

Five habits

Cache Select once, reuse the variable.
Batch Build off-page, insert once.
Delegate One listener on a parent.
Clean up Remove handlers you added.
1 / 2

Cache your selections

Every $("#panel .item") runs a search. Doing it inside a loop, an event handler that fires on every mouse move, or twice in one function repeats that search for nothing. Store the result in a variable and use the $ prefix by convention so you can tell it holds a jQuery object. The selector performance lesson goes deeper into context and ids.

JavaScript
// Slow and noisy
$("#panel").addClass("open");
$("#panel").find(".item").hide();
$("#panel").attr("aria-expanded", "true");

// Better
var $panel = $("#panel");
$panel.addClass("open").attr("aria-expanded", "true");
$panel.find(".item").hide();

Remember that a cached collection is a snapshot. Elements added later with .append() are not in it. If the list changes, either select again at the moment you need it, or use delegation so you never need the list of elements at all.

Batch your DOM changes

The browser can recalculate layout each time you change the page. Inserting 200 <li> elements one at a time asks it to do that work 200 times, while inserting them in one call lets it do the work once. Build the elements first, either in a detached container or as an array, and insert once. jQuery accepts an array of elements in .append().

One insert instead of two hundred

Two related tricks: when you must change a large live subtree many times, .detach() it first, edit the detached copy and put it back; and prefer changing a class over many .css() calls, since one class change applies a whole style block.

Delegate instead of binding many handlers

Binding a click handler to each of 500 rows allocates 500 handlers and forces you to rebind when rows are added. One delegated handler on the container handles all of them, including future rows. The pattern is covered in the event delegation lesson; the rule of thumb is: bind directly to elements that never change, and delegate for lists, tables and anything generated by script. Delegate to the nearest stable ancestor, not to document, because every event in the page would otherwise be checked against your selector.

Clean up what you add

A handler stays attached for as long as its element lives. Three situations cause real bugs:

  1. Binding twice. A function that attaches a handler is called again (after loading new content, say), and clicks now run the code twice.
  2. Handlers on document or window that outlive the widget that created them.
  3. Detached nodes still referenced by a variable or a handler closure, which keeps them in memory.

.remove() deletes an element and also removes its jQuery data and handlers; .detach() keeps them, so use it only when you plan to reinsert the element. For everything else, use event namespaces so you can remove exactly your handlers: .on("click.widget", fn) and .off(".widget"). The event basics lesson introduces namespaces.

The double-binding bug and its cure

Press Init again twice in each block, then click the button: the buggy one jumps by three per click, the fixed one by one.

Write readable chains

Chaining is jQuery's signature, but a chain that runs to ten calls on one line is unreadable. Put each call on its own line, indent the chain, and break it where the target changes. .end() returns to the previous selection, and .find() changes the target, so stop and name a variable when you lose track.

JavaScript
$("#menu")
  .addClass("ready")
  .find("a")
    .attr("tabindex", 0)
    .end()
  .on("keydown", onKey);

Prefer classes to chains of .css() calls, and prefer a small named function to a 40-line anonymous callback. Both make errors easier to trace.

Debugging checks that save hours

Most "jQuery is not working" reports have one cause: the selector matched nothing, and because jQuery silently ignores calls on empty sets, nothing seemed wrong. Check .length while developing.

JavaScript
var $rows = $("table.results tr");
console.log("rows found:", $rows.length);   // 0 means a typo, wrong timing or wrong page

Also look for the other common mistakes: running code before the element exists (use document ready), duplicate ids so $("#x") finds only the first, using .attr("checked") where .prop("checked") is meant (see attributes and properties), and forgetting that this inside a callback may not be the element you expect. The testing and debugging lesson goes into the tooling.

Security: never turn data into HTML by accident

Cross-site scripting (XSS) happens when text from a user, URL, cookie or server is inserted as HTML, so the browser treats it as markup and executes scripts or event attributes in it. In jQuery the dangerous methods are .html(), .append(), .prepend(), .before(), .after() and $() when you pass them a string containing markup.

  • Show data with .text(). It writes characters, never tags.
  • Create elements with an object: $("<a>", { href: url, text: label }). The text property is assigned safely.
  • Validate URLs before putting them in href or src: javascript: URLs run code.
  • Never call $(userInput). In jQuery 3 a string starting with < is parsed as HTML. A string that does not start with < is a selector, which can throw on odd characters and lets a user choose what you select.
  • Escape identifiers with $.escapeSelector() when an id or class comes from data: $("#" + $.escapeSelector(id)).
Text versus HTML for untrusted input

Replace the string with <img src=x onerror="..."> in a real page and .html() would run script, which is the classic attack. The sandbox here would contain it, but a production site would not.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is it better to append an array of 200 elements once than to call .append() 200 times?

    Each insertion into the live document can trigger layout work. Building the nodes first and inserting them together keeps that work to a minimum.
  2. 2. A function that attaches a click handler runs twice. What is the result?

    jQuery does not deduplicate handlers. Use a namespace with .off(".name") before .on("click.name", fn) so repeated initialization is safe.
  3. 3. Which line is the safest way to display a comment typed by a visitor?

    .text() inserts characters, so markup in the comment is displayed instead of executed. The other options can interpret the string as HTML.
  4. 4. What does $.escapeSelector("a.b") help with?

    It escapes characters that have special meaning in CSS selectors, so $("#" + $.escapeSelector(id)) matches the id literally.
  5. 5. A selector returns no elements and nothing seems to happen. What is the quickest first check?

    jQuery silently ignores operations on empty collections. A length of 0 points to a typo, wrong timing or the wrong page.

Summary

  • Cache selections in $-prefixed variables, and remember that a cached collection does not include elements added later.
  • Build elements first and insert them in one call; change classes rather than many styles.
  • Delegate from a stable parent for dynamic lists, and namespace handlers so .off(".name") removes exactly yours.
  • .remove() cleans up data and handlers; .detach() keeps them for reinsertion.
  • Break long chains over lines and check .length when nothing seems to happen.
  • Show untrusted data with .text(), build elements with property objects, validate URLs, never pass user input to $() and use $.escapeSelector() for identifiers.

Next: Testing and Debugging jQuery Code.