jQuery Event Delegation Improves Performance

In this post, I will share a simple tip of how you can improve jQuery performance by using Event Delegation to add event listeners to the parent element, and in turn, check for events on its children.

First let’s take an example where there are a bunch of ‘li’ elements inside an unordered list. We have to use jQuery to provide a click event and perform an action, when the user clicks on a li element.

For this example, we are converting the li into hyperlinks (not by appearance but by functionality)

jquery convert to hyperlink

The code shows a typical way of adding a click event to every ‘li’ element – there are three event listeners. However there’s a better way to do this using the jQuery delegate function and reducing the number of event listeners. Here’s how.

<script type="text/javascript">
    $(function () {
        $("ul").delegate("li", "click", function () {
            var loc = $.trim($(this).text());
            window.location = "http://" + loc;
        });
    });
</script>
Using the delegate function, we have added only one event listener on the parent element (‘ul’ in this case), and checking events on its children (‘li’ in this case). This tells the the ‘ul’ element to watch for click events on all ‘li’ elements, and if a click occurs, run the function.

The same event listener will be applicable to all ‘li’ elements that are added dynamically, i.e. at run time.
See a Live Demo





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

5 comments:

Anonymous said...

It might be a good idea to put the actual URL into a data attribute on the LI tag rather than relying on the list item's text.
- Gregg

Anonymous said...

Thank you Suprotim Agarwal for this useful performance trick.

@Gregg can you give example of what you are suggesting. Will your suggestion improve performance futher?

hqrts said...

Nice advice i'll take it into consideration for my future developments

Anonymous said...

Funny, no insight to how event's are handled by the browsers. Doesn't cover bubbling at all.

Anonymous said...

Ugh. While I completely believe the performance improvement claim - I hate it when it is thrown around without any benchmark to back it up. How big of an improvement is it? how does the number of children LI elements impact the performance delta? etc.

Just the same, I think there are other benefits in code readability and maintenance as well. Thanks for the reminder.