Search code examples
jquerylive

jQuery disadvantages of consistently using 'live'


Are there any disadvantages of using jQuery's 'live' consistently throughout my application?

If i attach click handlers to all my elements that i want and then decide to make my application AJAX, i'd have to go through and add a load of 'live' handlers in my jQuery.

I'm talking performance and HTTP requests etc...what are the disadvantages?


Solution

  • You should never use live. It was a mistake on jQuery's part when they introduced it. Only use delegate.

    When using live, jQuery will have to listen to every single click on the document. In most cases, this is overkill. Imagine this:

    <table id="products">
        <tr>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
    

    Now, you want to bind a click event handler on all of those rows. If you go the live way, you'll do this:

    $('tr').live('click', function(){...});
    

    What's happening here is that whenever any element on the whole entire page is clicked, jQuery will have to run it through your selector (in this case tr) to see if it matches. That is wasting a lot of resources for no good reason. You can accomplish the same thing by:

    $('#products').delegate('tr', 'click', function(){...});
    

    which will cause jQuery to only listen on click events inside that table (although it'll still run that selector check on every type of element clicked).

    Now, sometimes you really do need to listen for clicks on the entire page. But, even if you do need that, you're still better off using $(document).delegate('a', 'click', function(){...});.

    Why?

    Imagine the following scenario:

    $('a').live('click', function(){...});
    

    What you're doing here is traversing the DOM for all the a tags, but you're not doing anything with that collection. You're merely doing what you could've accomplished with:

    $(document).delegate('a', 'click', function(){...});
    

    but without traversing the DOM first!


    Further reading:

    http://api.jquery.com/live/#caveats
    http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/


    Update: With the advent of jQuery 1.7, the new .on method was introduced:

    The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

    So, in our examples above, you'd use this:

    $('#products').on('click', 'tr',  function(){...});
    

    and this

    $(document).on('click', 'a', function(){...});
    

    respectively.

    Although the old methods would still be functional, this is now the preferred way.