Article

Home » Client-side Coding » JavaScript & Ajax Tutorials » The JavaScript Library World Cup
SitePoint Feature Article

About the Author

Dan Webb

author_danW Dan is a rehabilitated DHTML hacker turned web application developer for Vivabit, organisers of the @media conference. His current weapons of choice are Ruby on Rails and modern, unobtrusive DOM scripting. On those occasions he's not programming, he enjoys blogging on Vivabit's blog, (The Web's Bollocks), hording vast amounts of vinyl and eating cheese slices.

View all articles by Dan Webb...

The JavaScript Library World Cup

By Dan Webb

June 14th, 2006

Reader Rating: 9

Page: 1 2 Next

Love them or loathe them, JavaScript libraries are making a huge impact in the area of DOM Scripting. As AJAX matures, and the complexity of the scripts required to support its expanding use increases, it becomes much less feasible to produce custom code from scratch for every project.

In addition, the growth of AJAX and the burgeoning interest in Web 2.0 applications is bringing many new people to the field. Not surprisingly, they don't want to spend the long, hard years absorbing the arcane knowledge required to wrestle with browser bugs and API differences.

Whether you're an old-school DHTML guru or a Web 2.0 wannabe, it's time you got to know some libraries. So, what's out there? I'm glad you asked!

Over the past year or so, as DOM Scripting has exploded in the mainstream coding arena on the back of AJAX, a seemingly endless number of JavaScript libraries have joined the list of contenders. Fortunately for our poor brains, there are four libraries that have emerged as the clear forerunners in terms of their levels of adoption, documentation and community support:

  • Dojo, a powerful library developed primarily off the back of JotSpot
  • Prototype, the backbone of Ruby on Rails excellent AJAX support
  • Mochikit, the Python library that makes JavaScript suck less
  • Yahoo UI Library (often shortened to just YUI), the new kid on the block

Of these four, there is no clear front-runner yet. Each library differs enormously from the others not only in features, but in less tangible aspects like ease-of-use, community support and philosophy. One of the most important factors in choosing a development platform is how well its philosophy fits with the way that your brain works.

In this article, I'll examine each library to help you decide which one best suits your development style and project needs. While it would be impossible to cover every aspect of each library, I've done my best to cover the highlights of each of them, as well as give some insight into how they handle the bread-and-butter tasks of DOM manipulation, event handling and AJAX.

1537_dojo

Dojo

Dojo is maintained by lead developer Alex Russell -- who recently announced that he would be working on Dojo full time -- and a group of around 30 core contributors. The library is primarily funded by Jot, creators of JotSpot, a souped-up Wiki engine.

Dojo can be downloaded from the Dojo site in several editions. Each edition bundles certain parts of the Dojo library into one JavaScript file, and allows you to load other parts of the library dynamically using Dojo's import mechanism. The most popular edition of Dojo is the AJAX edition, which weighs in at around 132K in its compressed form, and includes support for asynchronous I/O operations (for AJAX calls), visual effects, event handling and the Dojo base libraries.

Loading additional functions on top of an edition of Dojo is easy. If you wanted to add the crypto library, for example, you would write the following:

dojo.require("dojo.crypto.*");

However, for performance reasons it's best to choose your edition well, based on the needs of your project, and to avoid requiring extra libraries in this fashion.

Dojo definitely has the widest scope of the four libraries in terms of features, and pays more attention to tackling performance issues and browser compatibility issues. It has also been written with technologies such as SVG in mind, and moves are being made to bring the functionality of Dojo to SVG in a cross-compatible manner.

From dealing with strings as quickly as possible, to efficient iterations, to built-in support for the back button in AJAX, Dojo really has it all covered. However, this means it has quite a huge API, and the learning curve associated with Dojo is therefore substantial, given the sparse documentation at the moment.

Recently, the Django framework began to bundle Dojo with its distribution, using it in its administration system, so this may be a catalyst for increased Dojo documentation.

The Basics

At the heart of Dojo is a flexible, powerful and easy-to-use method, dojo.io.bind. This single method can be used in many ways to make both synchronous and asynchronous calls. To give you an idea of how flexible it is, let's take a look at some examples:

// Load a text document from the server, then alert the user of the contents.
dojo.io.bind(
 {
   url: "http://example.com/document.txt",
   load: function(type, data, evt) { alert(data) },
   mimetype: "text/plain"
 }
);

// Serialize a form and send it to the server, then evaluate the response as JavaScript!
dojo.io.bind(
 {
   url: "http://example.com/comment.cgi",
   load: function(type, json) { alert(json.myProp) },
   formNode: document.getElementById("formToSubmit"),
   mimetype: "text/javascript"
 }
);

dojo.io.bind can also handle the back button with ease:

dojo.io.bind(
 {
   url: " http://example.com/comment.cgi",
   load: function(type, data) { alert(data) },
   backButton: function() { /* do something when back is pressed */}
 }
);

Read more about the full capabilities of dojo.io.bind in this introductory article.

The dojo.event method takes the approach of implementing its own event handling system, rather than providing a wrapper around the browser's event system. This results in quite a solid system and, like dojo.io.bind, it's both simple to use and exposes large amounts of power and flexibility.

You can read more about Dojo events here. In the meantime, let's take a sneak peek at the dojo.event method in action. As expected, the following code is triggered by the onClick event and uses an intuitive and familiar syntax.

dojo.event.connect(node, "onclick", "handleOnClick");

Highs and Lows

The great thing about Dojo is that it's so rich in features. The Widget system provides a raft of useful controls such as a DatePicker, a RichText widget, as well as a considerable number of controls that you would expect to find in something like Microsoft's MFC. In addition to this, you can build your own widgets on the framework using HTML, CSS and JavaScript (see this article for details).

But JavaScript need not be limited just to the browser, and Dojo is designed with this in mind. Dojo's platform independence could make it an interesting platform for desktop widget development, as well as many other potential applications. As an example, Open Laszlo recently announced that it was licensing Dojo for its JavaScript implementation of the platform.

Dojo's design has quite a Java-like aesthetic without trying to be Java. In fact, I'd say Dojo utilises JavaScript as a language exceptionally well. One downside of the library's design, though, is the sometimes long package strings that you need to type out to call the methods or instantiate the library's objects -- it would be nice if Dojo could provide a way to "mix" a package into the global or local scope. This would provide ready access to a certain package if you planned on using a lot of methods from it, although I'm not sure how easily it could be incorporated.

Additionally, for all its features, Dojo is completely missing any functions that could aid the selection of DOM elements -- something that's quite fundamental to DOM Scripting. It seems to be quite a gaping hole in the library -- it would be great to be able to select elements using CSS and/or XPath. Similarly, while some of the objects in the library seem to support a kind of iteration framework, Dojo is lacking in methods for iterating though arrays and collections, a task which seems to make up the bulk of DOM scripting tasks.
And at this point in time, documentation for Dojo is not at a premium. The official Dojo site contains some API documentation that's far from complete, but it does have some well-written articles highlighting areas of the library. The JavaScript community has yet to embrace the daunting task of documenting Dojo, though, so independent on the topic articles are few and far between.

1537_protoscript

Prototype and Scriptaculous

The development of the Prototype library is lead by Sam Stephenson of 37 Signals and, along with scriptaculous, has risen to fame as the JavaScript backbone of Ruby on Rails AJAX helpers.

Prototype itself contains the base-level functionality such as AJAX, DOM manipulation, event handling and some extensions to JavaScript itself, while the separate but very much related library, scriptaculous, developed by Thomas Fuchs, is based on Prototype and implements a whole raft of visual effects, as well as drag and drop and some user interface components.

Prototype can be downloaded from the Prototype site, or you can pull it straight from the Ruby on Rails subversion repository if you want to live on the bleeding edge. It currently weighs in at a reasonably compact 54KB. scriptaculous is available from the scriptaculous site and is split into three files: controls.js, dragdrop.js and effects.js, which weigh in at 28KB, 23KB and 32KB respectively. Ruby on Rails bundles all of these files by default.

For an overview of Prototype, take a look at my earlier SitePoint article, Painless JavaScript with Prototype.

The Basics

As far as DOM manipulation goes, Prototype sits very much on the innerHTML side of the innerHTML/DOM methods argument,which may be a plus or a minus depending on which side of the fence you sit in that particular holy war.

Regardless, for most of the DOM lifting you'll need to do, Prototype is extremely useful. A new but very nice feature is that many methods are added directly into the nodes themselves. Here are a few examples:

$('form').visualEffect('fade', { duration : 3 });
$('loader').show();

This code fades out the form to which it is applied over a period of three seconds. You can even extend the node objects with your own methods. There have been some performance issues flagged with this approach, but I believe they have mostly been addressed.

Unfortunately, although Prototype has a set of methods for event handling, at this time they're pretty under-developed. Event.observe is more or less a wrapper around the well-used but now superceded addEvent by Scott Andrew-LePara. However, it's easy to use and capable of handling most circumstances. One nice aspect is that it automatically removes all the event handlers you set using Event.observe when the page is unloaded, which should help prevent IE from leaking memory.

The AJAX support is reasonably straightforward and very well developed, as it has been developed right alongside Ruby on Rails. It offers a host of excellent features that I find extremely useful.

It handles JSON transparently, and even evaluates JavaScript sent back from the server automatically. This is the basis of the much-lauded RJS technology in Rails, and is extremely powerful. You don't need Rails to take advantage of this, though -- you can make an AJAX request:

new Ajax.Request('new_comment.php',  
 {  
   data: 'comment=My comment.',  
   evalScripts: true  
 }
);

Then, you can return updates to the page from your server as JavaScript:

 $('comments').replace('<div class="comment">My  comment.</div>');

As you can see, this is an incredibly powerful way of designing AJAX applications.

Another nice little feature of the Ajax.Request object is that it appends the X-Requested-With HTTP header automatically, which enables you to tell if your requests come from AJAX on the server side.

Highs and Lows

Convenience is king with Prototype. Most notably, the $ function (which selects elements by id) and the $$ function (which selects elements using CSS selectors) provide extremely quick access to elements on the page. The $$ function even supports CSS3 selectors -- most browsers don't. When you use it in conjunction with the enumerable methods and Prototype's other convenience methods, you can come up with some pretty concise statements. For instance, to hide all div elements with a class of /#c#"obscene":

$$("div.obscene").map(Element.hide);
$$("a[href='http://']").each(function(element)  
 {
   Event.observe(element, 'click', openNewWindow);
 }
);

As we all spend most of our scripting time working through lists of DOM nodes, this buys us a lot of power indeed. The compact and intuitive API really is the killer feature of Prototype for me.

Scriptaculous is a great, extensive effects library with solid drag-and-drop support that, again, is ridiculously easy to use. Consider this:

new Draggable('my_element');

This produces an element that the user can drag. You can then add further configuration using object notation, like this:

new Draggable('my_element',  
 {  
   revert : true  
 }
);

Documentation was very limited for a long time, but recently many people have filled the gap, making Prototype one of the most widely documented of the big JavaScript libraries, albeit that that documentation is a bit splintered. There are no central API docs, but there's a whole raft of libraries that cover parts of the library, as well as Jonathan Snook's excellent cheat sheet detailing the entire library. The prototypedoc.com site also maintains a pretty thorough list of articles about Prototype to help you get started with the library.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article