5

I make a single-page application. When a hash is changed, new elements are loaded into a page via ajax.

I want to set an event handler to new elements. There are two ways.

  1. Every event handlers are delegated at start.

    $("body").on(event, "element", handler)

  2. Whenever a hash is changed, event handeler is direct-bound to new element. So, binding and removing handlers are repeated.

    $("element").on(event, handler)

Which performs better? (finding elements time vs. repeating bind-removal time) (Sorry, my english is poor...)

1
  • The only reason that doing it with dynamic delegation is quicker, is because of one less object that has to be constructed, assuming var $this = $(this); is used inside of both functions.
    – Ohgodwhy
    Commented Aug 1, 2013 at 5:45

1 Answer 1

1

It might help to have more information about how this single-page application works but perhaps you can consider these guidelines

  • How dynamic is your page? If it's fairly static (doesn't change, this may be a premature optimization)
  • How many DOM elements are involved here? The more DOM elements that need to be wired up individually, the more work must be done, more memory consumption, etc.
  • How deeply nested are your DOM elements? Deeper nesting, means more bubbling of events.
  • In the case of finding an element by id, the lookup from jQuery's perspective is extremely fast because DOM element id names are supposed to be unique and it typically just uses the getElementById native method.
  • In the case of finding elements by tag, you should have one body tag but you may have several hundred div tags if that's what you are selecting.
  • When you are still unsure, it's time to get Chrome Developer Tools involved to help you further fine tune and diagnose potential performance problems that you may experience.
  • jQuery's selector engine is extremely powerful and flexible, but not all selectors perform the same. You can write a gnarly selector that overburdens the browser unnecessarily.

In general, I usually utilize event delegation when I need a large group of items to behave similarly for a given event.

I hope this was helpful.

Not the answer you're looking for? Browse other questions tagged or ask your own question.