Tag Archive for 'programming'

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.

jQuery plugin: Awesomecomplete

L'Autocomplete

So I stayed up until 4am writing what I think is a pretty awesome jQuery plugin for doing autocomplete.

Edit 08/21: I changed the name from L’Autocomplete to Awesomecomplete on Sunil Garg‘s suggestion. Updated urls and code as appropriate, but this article remains as-is.

L’Autocomplete?

It’s what you get when I write a plugin at 4am. The L is supposed to stand for lightweight, which was one of the key design philosophies in terms of plugin responsibility. You’ll see. I think.

The apostrophe is there as a clever play on words to make it French: “The Autocomplete.” Well, clever for 4am, anyway.

Why bother?

The problem with most jQuery autocomplete plugins is pretty simple: they suck. My hope is that mine does not, but only time (and all of you!) will tell. While writing my plugin, though, I came to understand why this was the case: it’s rather difficult to write a flexible, customizable autocomplete plugin without ending up with somewhat of a shell of a plugin. After all, let us consider the critical components of implementing autocomplete:

  • Data retrieval. Where does my data come from? How do I format my request to the server and interpret what comes back?
  • Data format. What field am I searching against?
  • Data render. How do I display my list of options? What if I want to render a picture in the list? When the user selects a value, what data should I end up with?
  • Keyboard/mouse navigation. Wiring things up.

Apart from the last item — which, trust me, is the easiest part of the whole thing thanks to the magic of jQuery — everything else on that list is extremely contextual to the development environment. So how do you write a plugin where 80% of the potential code is hardly reusable? Some plugins take the end-all, be-all approach to this problem — account for all scenarios. I take the opposite.

As far as data retrieval is concerned, for instance, I leave that as an exercise to the developer. You give me a function to call when I need data from you, since you know how to get it. If your application has been written solidly, it’ll probably be a one-liner. I’ll give you a function to call back to when you get that data, and then we can continue on our merry. Of course, L’Autocomplete also supports loading in a prefetched cache of data — it’s actually the most useful in that case where it can see all available data at once, as you’ll see.

So what makes this particular plugin cool?

We’ve dealt with the data retrieval problem listed above in what I think is a lightweight and elegant fashion. You do it. The data rendering problem is really rather simple — I tell you all the relevant information about what you need to render, and you can give me a function that will do it. There are defaults that should actually work for 90% of you, though.

What makes the plugin cool, I think, is the solution to the data format problem. The obvious solution, since I’m making you do all this work of getting the data anyway, is to expect it in some kind of format — a list of strings, a list of key-value pairs, etc. I think this is a bad solution.

JavaScript is a dynamically typed language that’s trivially easy to reflect against. Why should I care what you give me? Just give me a list of whatever JavaScript model objects you use. You can specify the name of the “primary field” that will always be displayed (eg the name of a person), but the plugin will automatically parse every field in the object (you can of course tell it to skip fields you want left alone) for the search phrase, highlighting them if desired and telling you what field the best match was.

So, it’s an autocomplete plugin that works against multiple fields, with a pretty powerful and flexible search algorithm. There’s not much more to say about the design philosophy behind it, so onward!

Demo!

Go here for a demo running with some statically preloaded data. As a bonus to Safari and Firefox users, there are CSS3 rounded corners and drop shadows just for kicks. The data has names, emails, and phone numbers in it, so feel free to search on any of those. I should probably have included a mixed number-string field so that you can see that it’ll match any field on any item independently, but you’ll just have to take my word for it for now.

Get!

Drop by GitHub to get the code.

I’ll write some real documentation for the thing tomorrow.

Warning!

There are known issues in Safari at the moment, and the plugin is completely untested in IE, Chrome, and Opera. This is a preview release, of sorts.

I’m excited about the future of the web

Here’s what you can do today if you decide that you simply don’t care about 68% of the browser market:

Look ma, no images!

Doesn’t look like much, you say? Sure. It was just me screwing around while writing a throwaway prototype application. But what if I told you that what you’re seeing is pure HTML and CSS? There are absolutely no images involved in that entire layout. The tab even animates up and down, and the gradient fades in and out — with no images, and not a line of JavaScript.

It’s an old drum that’s being beaten to death, but this is why IE needs to either get with the game or go away. IE8 is at least a huge improvement in terms of respecting rendering standards, but with the gaping release cycle that Microsoft has IE trundling away on, they can’t possibly keep up with how quickly amazing features like these are coming along.

Just how quickly, you ask? Here’s what you can already do in the latest version of Safari/WebKit (even on the iPhone version!), with nothing but CSS, and JavaScript to push it along (source):

This has been proposed to the W3C. Everything you see is hardware-accelerated. I am stoked.

Expect a second edition of this post in a couple of days.