Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 855
Bojangles Avatar asked Aug 26 '26 10:08

Bojangles


1 Answers

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.

like image 67
maxedison Avatar answered Aug 28 '26 03:08

maxedison