Bojangles
Bojangles

Reputation: 101473

Performance of delegate()

I've been using $("body").delegate(".selector", "click", function() { ... }); for a while now, and I was wondering: If I delegate the click event to a containing element closer to the actual element, for example a table full of buttons, would this be faster than delegating the same event to body, seeing as the event doesn't have to bubble as far?

Basic HTML example:

<html>
    <body>
        <table>
            <tr>
                <td>
                    <input type="button" value="Delegated element">
                </td>
            </tr>
            <!-- More, identical rows -->
        </table>
    </body>
</html>

First example, using body:

$('body').delegate('input[type="button"]', 'click', function() {
    // Do things
});

Second example, using table:

$('table').delegate('input[type="button"]', 'click', function() {
    // Do things
});

Which of the two examples above is faster, and if one is faster than the other, why?

Upvotes: 3

Views: 1181

Answers (1)

maxedison
maxedison

Reputation: 17553

If I delegate the click event to a containing element closer to the actual element, for example a table full of buttons, would this be faster than delegating the same event to body, seeing as the event doesn't have to bubble as far?

Yes, it would be faster and precisely for the reason you suggest. I think this is a helpful article and fairly relevant to your question.

Upvotes: 5

Related Questions