Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Voices That Matter

Web Design Reference Guide

Hosted by

Prototype, Dojo, and jQuery

Last updated Oct 17, 2003.

By Faruk Ates

What do the three words from the title have in common? They’re all JavaScript libraries of some sort. There are far more libraries out there of course, but these three are fairly distinct ones and they’re all pretty popular. You can add an amazing amount of different JavaScript enhancements to your Web site with these scripts, but they also have their downsides. Plus, it’s very easy to get wrapped up in the features they offer and use them in places where they aren’t always necessary.

Note that these are three separate libraries that are maintained by different parties. They do overlap and are not made to be combined. I don’t recommend using more than one of them in the same page, as doing so might cause many headaches.

Also, we use the term "libraries" very loosely here, only because it keeps things more manageable. Prototype is a JavaScript framework, Dojo is a toolkit, and only jQuery can actually be considered a library—the semantics of which will be explained along the way.

Now, let’s take a look at what these scripts can (and can not) offer you.

Prototype

Prototype describes itself as "a JavaScript framework that aims to ease development of dynamic Web applications" and it certainly does what it claims to accomplish. Developed by Sam Stephenson, Prototype is currently in version 1.4.0, which we’ve used for this article.

When you start out with Prototype, you’ll immediately run into a problem: it doesn’t really have any official documentation. Fortunately, Sergio Pereira has created an unofficial Prototype.js documentation that explains all of the various helpers, functions, and extensions you can use once you include Prototype in your page.

So, what does Prototype let you do? Well, being a framework (as opposed to a toolkit) it doesn’t really offer any new functionality on its own. Instead, it makes it easier and faster for you to write your JavaScript applications. With Prototype, you get a large collection of helper functions and extensions that allow you to focus on writing JavaScript / DOM Scripting enhancements, cutting down development time and cleaning up your code drastically.

A good example of how Prototype simplifies development is the so-called Dollar Function. If you’ve written JavaScript before, you’ll no doubt be familiar with the document.getElementById() function. This, as the name implies, fetches an element from the document that has a certain id attribute. With Prototype, you can simply write the following:

var myElement = $(’elementid’);

However, unlike the document.getElementById() approach, using this function you can fetch multiple elements at once, simply by passing them as additional arguments to the function. The function will return an Array object containing your specified elements:

var myThreeElements = $(’elOne’, ’elTwo’, ’elThree’);

Similar to the Dollar Function are the $F(), $A(), $H() and $R() functions.

The $F() function makes it easy for you to get the value of any given form field. You can pass it the id of the form field you want, or simply the form object if you have it already.

The $A() function converts a single argument into an Array object, which can be quite useful. For instance, you could use it for converting DOM NodeLists into Arrays so that you can traverse them more efficiently.

With the $H() function you can convert objects into Hash objects, which you may know as associative arrays.

Lastly, the $R() function is a shorthand for creating an ObjectRange. Pass it a lower bound ("start"), upper bound ("end") and a boolean to exclude the bounds or not.

These are just a few of the shorthands that Prototype offers you, but they convey the essence and resulting code of the framework pretty well. There is much more, though, and we’re sure you’ll find one part of Prototype very interesting: the AJAX object.

In the Web of today, AJAX is becoming more and more popular and it, in turn, fuels people’s interests in JavaScript and the DOM. Prototype helps you out by making AJAX-development quick, easy, and efficient.

Imagine you’re creating an online bookstore in PHP and want to add AJAX to the search page so that visitors whose browser supports AJAX will get immediate results. You could have the following HTML code:

<form method="get" action="search.php" id="searchform">
  <label for="query">Search our online collection:</label>

  <input type="text" name="query" id="query" />
  <input type="submit" value="Search!" />

</form>
<div id="search-results"></div>

But thanks to Prototype, the JavaScript and AJAX work is as simple and clean as this:

Event.observe(window, ’load’, initialize, false);
function ajaxsearch(e)
{
  var url = ’search.php’;
  var pars = ’ajax=true&query=’+escape($F(’query’));
  var target = ’search-results’;
  var myAjax = new Ajax.Updater(target, url, {method: ’get’, parameters: pars});
  Event.stop(e);
}
function initialize()
{
  Event.observe(’searchform’, ’submit’, ajaxsearch, false);
}

The first Event.observe line calls the "initialize" function when the page is done loading. This function adds an onsubmit-event to the form which tells it to execute the ajaxsearch() function whenever the form is submitted.

The ajaxsearch() function will then make an AJAX call to search.php and put the result in our target div "search-results". The last line of the function, Event.stop(e); prevents the page from being submitted — which would render our efforts useless.

Note the parameter "ajax=true" in our example. This is optional, but it would let you use the search.php page for both AJAX and regular searches. You can simply change the output of the script depending on whether or not this variable is set to true. It is good practice to keep your site accessible, so if you do use AJAX to enhance your pages, make sure that a non-AJAX (and/or non-JavaScript) alternative is available to the user.

Furthermore, Prototype offers a variety of extensions, such as the Object.extend method, which lets you extend existing objects with methods and properties from another object. This can be extremely useful when you do a lot of Object-Oriented JavaScript.

Beyond the problem of the documentation, another downside to Prototype is that it is a 48 KB library (at the time of writing) which is quite a lot considering you’re using it as a base for writing your own scripts, which then add to the total download size. With some effort though, you can remove all objects, classes, and functions in Prototype that you don’t need (and that don’t have any dependancies, or you’ll break functions you do want to use).

All in all, Prototype offers a lot of improvements to the JavaScript development environment, making it a lot easier and faster to develop Web applications or simply enhance your pages. It also lowers the learning curve for JavaScript, so if you’re looking to get deeper into JavaScript and AJAX, give Prototype a try.

As a nice extra, there are some JavaScript libraries built upon Prototype, the most well-known of which is Thomas Fuchs’ Script.aculo.us library.

Dojo

The Dojo toolkit is very different from Prototype in that it is a toolkit, not a framework, and thus offers you a whole slew of functionality that is "plug and play"-ready. Dojo is being developed by the Dojo Foundation and the current release version is 0.3.1. It is an Open Source toolkit so anyone is free to work on it and contribute to the source.

With Dojo, you can enhance your pages in many ways, including but not limited to: visual effects and animations, drag-and-drop functionality, layout and form controls (called Widgets), and DOM manipulation helpers.

One of Dojo’s key components is its Event system. This system makes it possible and easy for you to keep track of any kind of event and perform functions at many events that can take place. With an Animation, for instance, you have the following events available to you:

* onBegin—fired when an animation is played from the beginning
* onAnimate—fired every iteration of the animation
* onEnd—fired when the animation has completed
* onPlay—fired when the animation is played from any point (including the beginning)
* onPause—fired whenever the animation is paused
* onStop—fired whenever the animation is stopped (by calling the stop() function, not by finishing) 

With Dojo’s Events system, you can very finely control almost every JavaScript-enhancement you wish to add to your pages.

Much like Prototype, Dojo also offers you a lot of DOM-related helpers, but unlike the former, Dojo doesn’t attempt to clean up code by using shorthands. Instead, you get a lot of additional DOM methods that use the same naming scheme as the original DOM methods themselves.

This has both pros and cons. Obviously, it keeps things more consistent with existing scripts, but it also keeps your JavaScript code fairly lengthy at the risk of feeling bloated and hard to maintain.

One of Dojo’s biggest and best features is its Widgets engine. Widgets are essentially HTML objects that you bind to JavaScript objects, which is a fairly vague way of saying they provide you with "templates" that you can use to quickly prototype (note the lowercase P!) your enhanced user interface in HTML and CSS.

Dojo comes with a lot of predefined Widgets that you can use as building blocks of sorts for all your sophisticated interface developments, but it also lets you create your own Widgets. This extensibility is not entirely similar to Prototype’s Object.extend method, but it is similar in that this lets you extend and expand on your scripts more easily and uniformly, which can be a timesaver as well as help keep things maintainable.

However, the Widgets system also highlights one of Dojo’s core problems at the moment: it is a huge toolkit. In fact, it is so incredibly big that Dojo is split up in dozens of smaller components that can be loaded when needed. This allows you to configure a base Dojo JavaScript file that only contains the core components that you truly need, a nice possibility since the default (compressed!) Dojo.js file that you get when you don’t manually configure it is a massive 132KB in size!

Another drawback to Dojo is that the documentation is very spread-out and incomplete, and sometimes downright vague. Unlike with Prototype, there aren’t a lot of great introductions to Dojo made by the community that allow you to circumvent this issue, so you may find that the learning curve for Dojo can be a bit higher than for Prototype. Can be, because some components (like the Animation classes) are a lot quicker to grasp and use than others (like the Widgets system).

Despite that, Dojo has many useful objects, methods, and helper functions to offer you that can greatly aid your developments. You can think of it as one (big) step further down the road from Prototype, offering you lots of predefined goodies that you can instantly use in your pages to add functionality, whereas Prototype makes it a lot easier and quicker for you to write such goodies yourself.

So how, then, does jQuery fit into all this?

jQuery

In the context of this article, the best way to describe jQuery, a library written by John Resig, is to say that it is a blend between Prototype and Dojo, positioning itself precisely in-between the two.

On the one hand, jQuery uses a shorthand syntax very similar to Prototype’s; they are not actually the same methods themselves, but similar in brevity and function. On the other hand, jQuery comes shipped with a lot of built-in functionality that goes beyond Prototype’s features and have a slight overlap with Dojo’s offerings.

For instance, with Prototype, you can easily select a certain object in the page with the following line of JavaScript:

var myElem = $("myElementId");

With jQuery, you’d write this:

$("#myElementId")

As you can see, jQuery bears a core similarity to Prototype, but there are two very important differences. One, jQuery allows you to "chain" functions and methods to this function; and two, rather than taking either an id value or a DOM object as argument, you can also feed jQuery’s Dollar Function an expression in CSS or XPath format.

Let’s take a look at a more complex example that shows off jQuery’s flexibility and power a little better:

$(document).ready(function(){
  $("div#controls a#showmenu").click(function(){
    $("#menu:hidden").slideDown("slow");
  });
  $("div#controls a#hidemenu").click(function(){
    $("#menu:visible").slideUp("fast");
  });
});

First of all, it deserves a mention that jQuery’s $(document).ready() function is a very welcome one, because it lets you manipulate the Document Object Model of the page when it’s ready, which is not necessarily the same moment that window.onload triggers. The latter method requires waiting for all elements to be fully loaded, including externally linked images, whereas $(document).ready() will trigger once the page itself has been loaded and the DOM is ready, which can be a lot sooner.

Now, the second line of the example shows how we’re searching for a div element with the id attribute "controls", then among the children of that element we’re looking for an element with a "showmenu" id attribute.

If that element is found, it adds an onclick function that, in turn, looks for an element (anywhere in the document) whose id attribute is set to "menu" and upon finding it, applies the "slideDown" effect to it. The ":hidden" part in the expression is a jQuery-feature that prevents you from applying the slideDown effect to an element that’s already visible.

The second batch of three lines adds the exact opposite functionality to a link that carries the "hidemenu" id attribute.

Somewhat similar to Dojo’s Widgets engine is jQuery’s built-in Plug-in system, which lets you extend jQuery with your own handmade methods that you can chain in the same manner as jQuery’s default methods. Because jQuery is designed to make writing JavaScript compact and fun, it is very easy to build powerful, clean plug-ins that vastly extend the amount of features that come with the base script.

Interestingly, jQuery excels in the two aspects that Prototype and Dojo did poorly in: documentation and script size. The base script is only 10KB in (heavily) compressed form, and the jQuery documentation is pretty descriptive and complete for all of the features it currently offers.

This leanness also explains its shortcomings compared to the other two scripts: while jQuery offers a lot of useful features and some basic animations, it can’t compete with Dojo in sheer number of them, nor can it compete with Prototype in the amount of useful shorthands and Event handlers.

Conclusion

All three scripts have their pros and cons that make them compete quite directly with each other. In the end, what script is best for you truly depends on your needs and preferences. If you’re looking for a massive feature set, go with Dojo. If you’re looking for optimizing your JavaScript writing techniques and cutting down on development time, try out Prototype. And lastly, if you want to have the best of both worlds and aren’t afraid to write a decent amount of functionality yourself, jQuery is worth a look.