JavaEnterprise JavaIntroducing Prototype and Scriptaculous Part 1

Introducing Prototype and Scriptaculous Part 1

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Ajax is growing up fast. One of the signs of that growth is the appearance,
and widespread adoption, of a number of third-party libraries that make
it easier to work with Ajax, and the web technologies that support it, such as
DOM, CSS, and, above all, JavaScript. This two part series covers two related
JavaScript libraries in depth: Prototype and Scriptaculous. Prototype provides
many small-scale features that make it easier to work with Ajax applications.
Scriptaculous leverages these features to build a number of higher-level user
interface components. Together, they can give your Ajax development the edge,
making it easy to express your ideas in JavaScript, and ridiculously easy to make
your user interface sing.

In this article and the next, we’ll set the scene for the Prototype and Scriptaculous
libraries, describing how they relate to the bigger picture of Ajax
development.

For your convenience we will take the libraries out for a quick spin in this article, using them to turbocharge a plain old Ajax application by cutting out a lot of
unnecessary low-level code, and making it easy to create a fluid,
pleasant user interface.

In the beginning of this article, we’ll concentrate on Ajax; that is, the business of
communicating between the browser and the server without causing
the full page to refresh. By the end of part 1, you’ll be able to make use
of Prototype’s support for Ajax in a variety of ways and we’ll
introduce an example application. In part 2, we’ll move on to look at Scriptaculous in more detail and at Prototype’s support for JavaScript and the DOM. We’ll begin, though, with a brief review of Ajax, in order to set the context in which Prototype and
Scriptaculous work.

A Brief History of Ajax

“Ajax” is a recently coined term used to describe the business of programming
highly interactive web-based interfaces using nothing more
than HTML, Cascading Style Sheets, and a good dose of JavaScript.
People have been writing this sort of application for several years, but
Jesse James Garrett only christened the practice in February 2005,
and it has since gone on to become one of the hot tech topics.

The adoption of Ajax by the web community has been rapid, and the
landscape has changed considerably. Prototype and Scriptaculous are
in the thick of these changes, and it’s useful to see where they’re coming
from. So, let’s briefly put our tech-archaeologist hats on and dig
through the history of Ajax.

Prehistory

If the history of Ajax began with Garrett’s article in 2005, then the discipline
has a rich prehistory, in which the techniques behind Ajax were
being explored without a name around which to rally the various practitioners.
Ajax was first made possible by the invention of an ActiveX
component called XMLHttpRequest. This component allowed web
applications to contact the web server without refreshing the entire
page, but rather passing the response to a script for processing. These
hidden requests for data are generally referred to as “asynchronous,” a
term that provides the first “A” in Ajax. Browsers had long been able to
manipulate the user interface programmatically using the Document
Object Model (DOM) and Cascading Style Sheets (CSS), but without
the ability to fetch anything new from the server, full-page refreshes
were still frequent. Adding XMLHttpRequest into the mix made it
possible for an entire application workflow to be encapsulated within a
single web page, which simply reorganized itself in response to asynchronous
requests for data made while the user was working.

Technologically, this was a cool new toy to play with. In usability
terms, it offered a major breakthrough, because it allows the user to
continue working while the browser waits for the server to respond to
a request. Without Ajax, web-based apps are characterized by frequent
periods of inactivity while a new page is requested, and this stop-start
pattern is unsuitable for any serious application. Nonetheless, webbased
apps are beloved of tech support departments because they don’t
need to be installed on the user’s machine, and can be upgraded
instantly. The tension between these two factors is resolved by Ajax,
making Ajax-powered web apps a compelling alternative to desktop
apps and thick clients in a wide variety of applications.

XMLHttpRequest was made available with Internet Explorer 5,
in 2000. However, the adoption of Ajax didn’t happen then. Everyone
who saw Microsoft Exchange Web Mail thought it was pretty neat,
but few rushed in to copy it. Maybe the fact that it relied on ActiveX,
and was therefore limited to Microsoft operating systems was seen as
too great a drawback. Maybe broadband penetration wasn’t sufficiently
advanced to consider providing apps that required a constant
connection to the server. Maybe it just looked too complicated or different.
Whatever the case, the capability wasn’t exploited by many, and
it would take several years before widespread interest in the techniques
developed and the barrier imposed by the stop-start workflow was
finally lifted.

The Pioneer Phase

In these days of Ajax prehistory, a few hardy individuals-Eric Costello,
Erik Hatcher, and Jim Ley, to name but three-explored the
possibilities of communicating asynchronously with the server, and
they even published descriptions of the techniques that they developed,
sometimes using XMLHttpRequest and sometimes falling back on
other browser features such as IFrames to enable asynchronous traffic.
As well as these publicly visible efforts, several corporate or private
developers (including ourselves) were also discovering the techniques
and putting them to use internally.

Another group of pioneers deserve a mention in this section. These are
the people who were exploring the JavaScript language and the
browser environment in which JavaScript commonly sits. Doug
Crockford did pioneering work on object-oriented JavaScript techniques
back when it was generally regarded as a toy for script-kiddies.
Piers-Paul Koch explored the intricacies of cross-browser behavior,
and Dan Steinberg and Mike Foster developed entire frameworks for
cross-browser DOM manipulation, some of which even predated
XMLHttpRequest’s first appearance. JavaScript is the glue that holds
Ajax applications together, and their work has done a great deal to
inform current thinking on Ajax web development.

When “Ajax” became a household name, then, there was already a rich
seam of work by Crockford, Koch, and others waiting to be discovered.
However, communication between these various efforts was limited,
given the low profile of the subject prior to 2005, and the early
Ajax landscape consisted largely of roll-your-own solutions and makeshift
frameworks. With more eyes on the subject of developing large,
robust JavaScript applications, though, the amount of effort in this
area intensified.

The Settlers Arrive

The year 2005 saw an explosion in the number of Ajax and JavaScript
frameworks, helper libraries, and other projects aimed at assisting in
the development of Ajax apps. Ajax in Action (by Dave Crane and Eric
Pascarello with Darren James) included a list of over forty frameworks,
and several were certainly left out. The pioneers were being followed
by a wave of settlers, staking out territory and busily setting up
small settlements. Inevitably, some of these withered, and others grew
into small towns. Over the next year or two, we can expect to see a
reduction in completely hand-coded Ajax applications, as best practices
and the results learned from other peoples’ mistakes crystallize
into frameworks and utilities.

Prototype and Scriptaculous are two of the more successful of these
JavaScript frameworks, and they have grown quite a community in a
short time. (In fact, according to the Ajaxian.com 2006 frameworks
and libraries survey, Prototype and Scriptaculous dominated the field
at 43 and 33 percent adoption respectively.) A large part of their design
is focused on making Ajax development faster, easier, and more enjoyable.
The impact of these, and other, frameworks on the nature of Ajax
development is likely to be considerable.

Civilization

That brings our history of Ajax development up to the present day. The
phase that we’d consider analogous to “civilization” hasn’t happened
yet (and we won’t even stop to consider the subsequent descent into
barbarism that tends to plague real-world empires!). There are still
many ways to get the job done using Ajax, and many of these ways are
only partly compatible. In this article and the next, you’ll learn the details of one particular way, but we’ll also look at how Prototype and Scriptaculous can
interact with other popular frameworks.

And so, without any further ado, let’s start to unpack Prototype and
Scriptaculous, and see what they’re capable of.

What is Prototype?

We’ll look at Prototype first, because it is the more fundamental of the
two libraries. Prototype provides a set of language extensions for Java-
Script, for the browser environment, and for the XMLHttpRequest
object. Scriptaculous (and other libraries, such as Rico) build on Prototype’s
foundations to create widgets and other end-user “stuff.”

It might seem odd to state that a JavaScript library can extend the language
in which it was written, but that’s exactly what Prototype does.
JavaScript provides a mechanism known as prototype-based inheritance
(from which this library derived its name). In fact, several scripting
languages provide features for extending the base objects of the
language. Ruby does it, and many of the extensions provided by Prototype
are borrowed from Ruby. Once could describe Prototype’s goal as
making JavaScript feel more like Ruby.

The good news for most of us is that it isn’t necessary to understand
everything that’s going on under the hood in order to get the benefits
of Prototype.

Right now, though, we’ll run through the features that Prototype does
provide, in order to give a more concrete sense of its scope and the
issues it is designed to address. We’ll group these into features that
address the core language, and those that are designed specifically for
web browsers.

JavaScript Language Features

JavaScript is a general-purpose programming language. As an Ajax
developer, you’ll generally be using Prototype inside a web browser,
but certain parts of it, such as objects, features, arrays, strings, and
numbers, are designed to enhance the JavaScript language itself.

The JavaScript Object Class

At the core of most JavaScript programming is the base class Object.
Creating an Object in JavaScript can be accomplished in as few as two
characters:

var myObject = {};

myObject is endowed with a number of useful features and methods,
such as a toString() method, the prototype-based inheritance mechanism,
and the ability to absorb new properties and methods on the fly.

Using the prototype property of Object, it is possible to create proper
object-oriented hierarchies of object types similar to those that a Java
or C# programmer would be used to. That is, it’s possible, but it is rather
cumbersome. Prototype adds some useful features to the Object that
make it a lot easier and more natural to develop object type hierarchies.
We’ll see these capabilities in action as we examine other parts of Prototype,
and Scriptaculous, which makes heavy use of these functions.

JavaScript Functions

JavaScript Function objects represent pieces of code that one can call,
passing arguments into them, and that will return a result. In this,
they’re very similar to the methods that OO-programmers attach to
objects.

A JavaScript function, unlike a Java or C# method, is a first-class citizen
in the language. It can be referenced directly, passed as an argument
to other functions, and even attached to arbitrary objects. This
freedom gives the JavaScript programmer the opportunity to indulge
in all sorts of strange and clever hacks. For the more practical among
us, understanding JavaScript Function objects is important because
the browser event model relies upon them. Prototype comes to our rescue
here again, making it easier to bind Function objects to JavaScript
objects in the way that the event model commonly calls for.

JavaScript arrays

In JavaScript, arrays are expandable, numerically indexed lists of variables.
The base language supports accessing array members using
square braces notation, like this:

var element = myArray[3];

Iterating through the members of an array is generally done using a

for() loop, like this:
for (var i=0;i

The Ruby programming language has a much richer way of interacting
with arrays, based on an Enumeration type. Prototype has ported this
concept over to JavaScript, and enhanced the native arrays with a similar
functionality. If you're used to working with Ruby's Enumerable
types, Prototype offers a home away from home. And even if you don't
know Ruby, Prototype's array extensions are easy to pick up, and will
soon become a powerful addition to your repertoire.

JavaScript Strings and Numbers

The String and Number classes in JavaScript allow methods to be
attached to the language primitives directly. Functions attached to
strings can be called directly from the primitive:

"abcdefghijklm".substring(4,10)

This line will evaluate to the string "efghij", for example. With numbers,
it is necessary to reference the number as a variable first:

var x=123456789; x.toExponential()

This evaluates to the string "1.23456789e+8".

The standard methods on JavaScript primitives mostly relate to formatting
and some helpers for generating HTML content. Prototype
extends both String and Number with some useful utilities that make it
easier to work with HTML colors, that support internationalized text,
and other useful features.

That wraps up the features of Prototype that affect the core JavaScript
language. Let's look now at what Prototype can do specifically within
the web browser.

Web browser features

More lines of JavaScript code have been written for use inside web
browsers than for any other environment. When coding in such an
environment, various parts of the web browser are exposed to the JavaScript
interpreter, and Prototype offers support for the web coder in
various ways. We'll map out the territory here.

The Document Object Model

The Document Object Model (or DOM for short) is the mechanism
by which the visual elements of a web page are exposed to the JavaScript
interpreter. When we hide or show on-screen elements in
response to a mouseclick or keypress, build a DHTML navigation
menu, or create a browser-based animation, we're using the DOM.
Programming the DOM used to be a major exercise in cross-browser
workarounds and tricks, but the major browser vendors have converged
around the W3C standards in recent years, and cross-browser DOM programming
is no longer the problem that it was. However, the
W3C model is rather verbose and unwieldy, and writing code against it
can become an exercise in stamina.

Prototype provides a few helper methods that ease some of the strain of
DOM programming. For now, let's continue our quick tour of Prototype's features.

HTML Forms

HTML forms are a mainstay of web application development, and, in
the pre-Ajax era, presented the only serious way to elicit information
from a user. With Ajax, other input mechanisms, such as drag and
drop, can be used as part of a conversation between the browser and
the server, but forms still have a very important role to play. Prototype
provides a set of utilities for working with HTML forms.

JavaScript Events

Event handling is central to the Ajax user interface. Although the
major browsers have converged in their DOM-manipulation APIs, the
event models of the Internet Explorer and Mozilla browsers still differ
considerably, in both the calling semantics and the implementation
details. Prototype provides some excellent cross-browser support when
coding events, and it also extends the Function object to make it easy to
work with event handling, as we noted earlier.

Ajax Utilities

The final feather in Prototype's cap is its support for Ajax. All major
browsers support a version of the XMLHttpRequest object that makes
Ajax possible, either as an ActiveX component or as a native JavaScript
object. XMLHttpRequest, however, exposes the HTTP protocol
at a very low level, which gives the developer a lot of power, but also
requires her to write a lot of code in order to do simple things.
Prototype uses its own object inheritance system to provide a hierarchy
of Ajax helper objects, with generic base classes being subclassed by
more focused helpers that allow the most common types of Ajax
requests to be coded in a single line. By making Ajax this easy, Prototype
provides even more value to web developers.

Prototype provides an extremely solid foundation for developing complex,
well-structured code, but on its own does little beyond that. The
onus of developing the functionality that the end user will see still rests
firmly with the developer.

Editor's Note: To see the last part of this series go to Introducing Prototype and Scriptaculous Part 2.

About the Authors

Dave Crane is an Ajax authority and lead author of the best-selling Ajax in Action. He is currently senior developer for UK-based Historic Futures Ltd., developing the next generation of socially responsible supply-chain systems using Ajax to link rural cooperatives and multinational corporations.

Michael "Bear" Bibeault is a US-based Java programmer with over 20 years' experience in enterprise and Web applications. He's a popular moderator on The Java Ranch and coauthor of the upcoming Ajax in Practice.

Tom Locke is an UK-based independent web developer and trainer specializing in Ruby on Rails. He is the creator of Logix, a multi-language programming system, and the CTO of LiveLogix.

Source of This Material

Prototype and Scriptaculous in Action
By Dave Crane and Bear Bibeault with Tom Locke
ISBN: 1-933988-03-7
Published by Manning Publications Co., March 2007
Paperback: 544 pages, Retail price: $49.99

MEAP + Softbound print + ebook - $49.99
MEAP + ebook only - $25.00
This material is Chapter 1 of the book.
Reprinted with the publisher's permission.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories