Performant .live() in jQuery 1.4

So, jQuery 1.4 has very few new features that really make the upgrade worth it (though fixing the .val() on checkboxes and radiobuttons and implementing .detach() are both things that should have been done long ago), but the performance benefits are immense in some cases, so I decided to move the in-progress odkmaker project over.

One significant optimization I’ve been using with jQuery 1.3.2 for some time now was documented by Zach Leatherman — when you use .live() (and if you have a dynamic number of elements you should always be using .live() over .bind()), there’s actually a pretty horrible inefficiency inherent in the way it’s called. Read his post to get the in-depth explanation, but essentially you’re calling into the Sizzle engine to evaluate your selector, when really .live() only cares about the text of the selector. Zach’s method fixes this problem, but unfortunately due to some internal changes in jQuery 1.4, his brilliant method has stopped working.

Thankfully, the fix is pretty simple. The critically missing part is that jQuery objects now have a reference to their context, I suppose to ease use between frames. The resultant code is as follows:

;(function($)
{
    $.live = function(selector, type, callback)
    {
        var obj = $([]);
        obj.selector = selector;
        obj.context = document;
        if (type && callback) {
            obj.live(type, callback);
        }
        return obj;
    };
})(jQuery);

So in the future, instead of

$('a[rel="modal"]').live('click', function(event)
{
    /* some code */
});

you should write

$.live('a[rel="modal"]', 'click', function(event)
{
    /* some code */
});

And thus you save the cost of iterating through the whole document for absolutely no reason.

This technique shaved off up to 7 seconds on pageload on a commercial-grade website I work on, so it would be a huge loss if it stopped working — it’s good news that it’s so easy to fix.

0 Responses to “Performant .live() in jQuery 1.4”


  1. 1 파워볼
Comments are currently closed.