Virtual Brain Online Logo

Bookmark: Root \ Webdesign \ Create rich client apps with the DOM

Create rich client apps with the DOM


Last Updated: 2005-12-10

By Mike Padilla - 2004-03-24

Exploit the Document Object Model to create enhanced Web applications

Move your Web applications beyond the handicap of the ubiquitous thin client architecture. Today's browsers finally support advanced client-side interactions across all objects in an HTML document. Thanks to the Document Object Model (DOM), UI designers can now create interfaces that let users manipulate data in real time while still offering the conveniences of a Web application. Author Mike Padilla shows you how to implement code that exposes robust client-side functionality that is both clean and extensible.

As the browser wars come to a close, user interface (UI) designers and developers are left with a fairly fixed, robust platform on which to create better Web applications. The latest browsers afford you two things: more control over how the UI behaves on the client side (both visually and interactively) as well as cleaner, more extensible ways to implement it.

Yes, developers can start to have their cake and eat it too, as the chains of the standard Web application -- a thin client working in conjunction with a server -- continue to break. Today you can create applications with rich interactive functionality that are easily deployed and upgraded on the Web. This is a result of the development, acceptance, and adherence to standards regarding the Document Object Model (DOM). UI designers and developers can leverage the DOM's accessibility and manipulability through JavaScript and cascading style sheets (CSS) to create systems that users can manage more efficiently.

You want it fast, you want it now

Imagine if, for every meal you make, you have to go to the grocery store and purchase only the food you need for one meal. If you forget a key ingredient, you have to return to the store. You also have to throw away any leftovers. You don't have a refrigerator or cabinets to store any items. When lunch rolls around, so does another trip to the store. The same holds true for dinner. And because everybody must make a trip to the store for every meal, the store can become rather congested.

Oh yeah, and in your kitchen, all you have is an open flame and a single spoon with which to cook. Not very efficient, is it? However, this is basically how today's thin client applications work. Nearly all resources exist at the server (the store), while the user must make several time-consuming attempts to access those resources, only to be used once in a tightly controlled, limited manner (basic form entry/submission).

But what if Web applications worked in the way you actually operated in the kitchen? You go to the grocery store once a week, purchase a wide selection of items, and then bring those items home for your immediate use throughout the week. You have a wide assortment of tools that make cooking not only easier but also more enjoyable.

You can implement a Web application based on such logic through a rich client, where the application is optimally dispersed across multiple tiers. Sets of data, business logic, and highly interactive UI elements can be downloaded to the client for instant user interaction. The result: the best of both worlds. You have the deployment ease of a networked application and the efficient functionality of instantaneous response.

Is thin still in?

Nearly all Web sites and Web applications today are thin clients, with a data set and a minimal presentation layer downloaded to the user's PC, while the bulk of computational processing occurs at the server. The primary benefit of a thin client architecture model is deployment ease -- by changing the source in one location (the server), users are instantly upgraded when they return to the application. Compared to the behemoth task of manually upgrading a user base with a locally installed application, the effort required to upgrade users with a thin client application is minimal. The ability to easily deploy new application releases without requiring users to install additional software is very appealing.

With a thin client, you can maximize the one resource you have complete control over, the server, to do the brunt of the work and dish out a minimal set of data and presentation layer information.
Nothing but skin and bones

But how efficient is it to have a big powerful server crunch computations while countless client machines receive its information? Not very. In between the almighty server and submissive clients is a little problem called limited bandwidth and its resulting demon -- server lag. The user fills out an order form, submits it, and waits six seconds. A screen renders, showing errors in the form submission. The user attempts to correct the errors and resubmits. Twiddling thumbs, the user waits another six seconds. And on and on.

Even with the increasing availability of broadband, client-server delays (those greater than one tenth of a second) still pose usability problems. Users no longer feel like they're operating with the UI directly. At around 10 seconds, users lose their train of thought and you risk losing their attention. The server is powerful, but without a user accessing its data, it becomes ineffective.

Another crippling characteristic of thin clients is that nearly all user interaction is at the page level. Systems primarily respond to the user page by page rather than elementally at the HTML component level. Such macro-level system response is inefficient because many user interactions warrant an immediate response. The cumulative effect of executing smaller instantaneous interactions is often the most efficient way to accomplish a larger goal. Imagine if instead of keys for individual letters, a keyboard displayed keys for entire words. That would make things quite slow and awkward. And that's what best describes the interactions forced at higher aggregate levels. Such interactions are synonymous with thin client applications.


Not too fat, not too thin: the rich client

The only way to eliminate, or at least minimize, the disruption in workflow caused by server lag is to download data and functionality directly to the user's computer. Only then can the user manipulate the data with the near instantaneous response of a true local application. But how much should you download to the user's local machine?

With a client-server application, you have a wide spectrum of implementations, from fat client to thin client. An extreme fat client downloads the entire application and only calls the server when data needs to be exchanged. The application's entire UI, along with all application logic, resides on the user's machine. At the other extreme, a thin client downloads only a small parcel of data with a minimal set of UI.

A fat client application's enhanced performance comes at the expense of a significant initial download and installation. As such, any changes to the application require a laborious upgrade across the entire user base. In addition, fat clients are not built on frameworks as open as traditional Web applications. Thin client applications allow ease of development, deployment, and upgrading; however, the user usually suffers from the delayed ping-pong of client-server communications. The best solution today lies in the middle of these two extremes: the rich application.
Defining the spectrum of client-server architectures

So what exactly is a rich application? No binary answer distinctly defines it. Even within the niche of rich applications, a wide spectrum of rich client functionality exists. Applications developed using Macromedia's Flash are often referred to as rich applications. But such applications require a browser plug-in along with the specific application download. Depending on how you utilize Flash, the application can fall in the rich client category or in the realm of fat applications.

The same holds true at the opposite end, where HTML Web applications using basic CSS and JavaScript provide enhanced client-side interactions and data manipulability. Such applications teeter between thin client and rich client. While the rich client lies between the thin client and the fat client, it comes in many gradations. Essentially, a rich client offers nearly the same deployment ease as a thin application with nearly the same enhanced interactivity and usability of a fat application, along with improved server resourcing.
Strike it rich

Rich clients certainly sound like the optimal method, so why haven't they been widely used? Until recently, the browser market has been plagued with high fragmentation and immature functionality. With the browser serving as the primary platform for most Web applications, the task of developing advanced client-side functionality has been extremely difficult.

Two major events transformed the landscape. First, by exposing the DOM, the W3C has developed and stabilized universal standards for defining advanced client-side functionality. Second, while Microsoft's Internet Explorer clearly dominates the browser market, it generally supports those standards. This means UI designers and developers now have a fixed, robust platform and can feasibly create rich client applications that leverage advanced, instantaneous, client-side interactions.


What a rich client can do for you

Imagine if you could reference any HTML element rendered on the screen, change its properties, set handlers triggered by events, and modify its appearance -- all instantaneously. Well you can. With the W3C-defined DOM, you can programmatically access and manipulate a page's elements and their corresponding attributes.

Whereas before a UI designer was primarily limited to page-level interaction, now he can design complete interactivity at the element level. Anything from table cells to form fields to links, you can uniquely reference and modify client side through both their attributes and CSS properties. You can make each screen more like a mini-application. A set of data with a dynamic set of UI can be downloaded to the user's machine, where the user manipulates the data in real time through advanced, more efficient interactions.

The standard level of interaction with a basic Web application is simple form data entry with a static set of information. At this level of interaction, the user is stranded on a small barren island of limited functionality.

A rich client application, instead, reveals a paradise. Since the set of UI delivered to the user is rich in functionality, the user can quickly and easily manipulate the data extensively before making a server hit (and taking the corresponding performance hit). For a basic data form entry screen, such as an online credit card application, a rich client gains little, if any, performance boost because the user activity is limited. Client-side data validation, which may be considered basic rich client functionality, would provide some value. Beyond that, however, not much more interactivity can improve the data entry process. As you start to implement Web applications as true applications that require significant data manipulation, a rich client design can greatly improve user efficiency.

Rather than make the user a slave to the application, requiring frequent trips to the server, the rich client application puts the user in control. To a far greater extent, you can implement the usage paradigm of traditional applications, where a user manipulates data and proactively (at the user's command, not the application's decree) saves the changes.


Rich client: Under the hood

* Elements: The "nouns" in the HTML code; things like tables (<table>), rows (<tr>), and links (<a>)
* Events: Triggers that are set off by user or system initiated actions
* Attributes/Properties: The "adjectives" of the elements
* Styles: Similar to attributes/properties, with some overlap; styles are more extensively defined to cover greater detail with CSS

When working with these four pieces, you can dictate that when a specific event occurs, an attribute of a particular object must change. You can do this for everything on the page.

Listing 1. Figurative example code



<baby id="babyJoe"
onCry="checkCry(this)"
style="personality:cute"> I am cute </baby>

function checkCry(babyFocus) {
if (babyFocus.wetDiaper) {
changeDiaper(babyFocus);
babyFocus.style.personality = "happy";
}
}

Not only can you reference existing HTML elements, you can also insert new nodes into the document. You can seamlessly remove nodes as well. Need an extra row in that table? Just add one on the client side: tbody.insertRow(0). Need to remove a row? Rip it out: table.deleteRow(0). No trips to the server are needed and the user is in complete, instantaneous control.


Clean and extensible implementations

Style sheets are a great way to link presentation display to a single source. Imagine if you could do the same with behaviors -- if you could just as easily assign behaviors to a table cell, like expand and collapse, highlight or scroll, as you could set its background color. Well guess what? You can.

The W3C has documented submissions for including behavioral extensions to the CSS specification. These extensions let you attach standalone behaviors to any HTML element through a CSS class. Although a universal standard has not been adopted, Microsoft has implemented a proposed solution using HTML components (HTC). Functionality specific to Internet Explorer 5+, HTC behaviors lets you add events and their corresponding actions all through a CSS-assigned class. For example, say you have a text field that highlights when the user mouses over it, expands when the user clicks it, and copies its content as the user types in it. Traditionally the HTML code for this would look like:
<input type="text" name="textfield" onMouseOver="highlight(this)" onClick="expand(this)" onKeyUp="copyText(this)">

Using HTC behaviors, this all boils down to just:
<input type="text" name="textfield" class="dataCell">

That's right. You can control the behavior of HTML elements with the same simplicity and extensibility as controlling their appearance. Rich client development doesn't have to come at your code's expense. By utilizing HTC behaviors, your code can be just as clean and partitioned as before.

Using HTC behaviors entails three components:

1. CSS class
2. An HTC file
3. A Web page (HTML, JSP, ASP, and so on)

The CSS class links to a behavior in an HTC file. The HTC file specifies the event and functions to perform. By assigning a class to an HTML element in a Web page, the behavior as defined in the HTC file is seamlessly applied.

The following listings add a highlighting behavior to a text field through CSS and an HTC file.
Listing 2. The HTML code


<input type="text" class="highlightingCell">


Listing 3. The CSS class


.highlightingCell {
behavior : url(/javascript/ highlightingCellBehavior.htc);
background-color:'';
border:none;
height:13;
width:100%;
text-align:right;
}


Listing 4. The HTC file code (file named highlightingCellBehavior.htc)


<PUBLIC:COMPONENT URN="projectOneBehaviorOne" >
<PUBLIC:ATTACH EVENT="onfocus" ONEVENT="cellOn()" />

<PUBLIC:ATTACH EVENT="onblur" ONEVENT="cellOff()" />
<SCRIPT LANGUAGE="JavaScript">
function cellOn()
{
window.event.srcElement.style.backgroundColor='#FFFF99';
}

function cellOff()
{
window.event.srcElement.style.backgroundColor='#FFFFFF';
}
</SCRIPT>
</PUBLIC:COMPONENT>


Of course, a Microsoft-only solution is not necessary for a clean implementation with DOM. Using the addEventListener method, you can add events and corresponding functions to any HTML element. Although not as clean and extensible as HTC behaviors, this method still lets you attach behaviors from one source without having to explicitly define which events and functions are associated to every HTML element. Here's how it works:
Listing 5. Code for addEventListener method



the HTML:
<td id="myCell">

the JavaScript:
//define the object
var obj = document.getElementById("myCell");
//attach the behavior to the object
obj.addEventListener("mouseover", highlight, false);

This results in the equivalent to:
<td id="myCell" onmouseover="highlight()">

Internet Explorer has not adopted this DOM standard; instead, it uses a similar method: attachEvent. For Internet Explorer, the code would be:
Listing 6. Code for attachEvent method


the HTML:
<td id="myCell">

the JavaScript:
//define the object
var obj = document.getElementById("myCell");
//attach the behavior to the object
obj.attachEvent("onmouseover", highlight);


By looping through multiple HTML elements, you can quickly and cleanly apply behaviors to each one. This is easily facilitated by using sensible IDs (such as TopCell1, TopCell2, and so on) or by navigating through the node structure of an HTML element (such as, looping through all the td elements in a specific tr node using childnodes.length). You may also use the getElementByTagName function to focus on HTML elements of certain types to which you may want to attach behaviors.


The rich get richer

Rich client functionality results in each page of the Web application acting essentially as a mini-application. Users can modify data and screen elements instantly by directly manipulating the UI on the their machines. Whether the user needs to add more rows to a table, sort the data, enter new data, edit multiple records, or copy and paste complete recordsets, they can do so quickly and efficiently on the client side, without the server delay.

Rather than serve multiple dumb pages, a rich client application can leverage its architecture to create smart pages. By optimally distributing the load across both client and server, users benefit from improved system response and an application performance boost due to better server resourcing.

Web applications can begin to break the chains of their thin client ancestors, which offer easier deployment of a networked application at the expense of user efficiency. With standards maturing and browsers' increasing compliance to those standards, UI designers and developers can now implement rich client functionality in clean and extensible ways, making life better for the users and developers alike.


Resources

What is DHTML?
Dynamic HTML is a set of technologies that provide Web developers with a high degree of flexibility in designing and displaying a user interface. DHTML consists of scripts, style sheets, and a new and improved document object model (DOM).

DHTML's biggest advantage is that once a Web page has loaded, a majority of user interactivity can occur completely on the client side, without hitting the Web server. However, DHTML has disadvantages, too. The greatest disadvantage being that two different implementations exist (for Netscape Navigator and Microsoft Internet Explorer) and are found only in the more recent browser versions.

* Learn all about the DOM directly from the source at the W3C.

* Visit this HTML and DHTML Reference for a cross-linked list of attributes and properties.

* Try the Gecko DOM Reference, the source for Gecko implementations of the DOM.

* Learn more about "JavaScript and the Document Object Model" in Nicholas Chase's introductory article (developerWorks, July 2002).

* Improve usability with client-side scripts in "Using Web widgets wisely" by Jodi Bollaert (developerWorks, September 2002).

* Check out Jeremy Allaire's whitepaper "Rich Clients and the Internet Experience" (pdf, 486Kb) for a good overview of why rich clients can enhance the user experience.

* For a peek into what the future of the Internet may hold, with the help of rich client Web applications, take a look at Forrester's George Colony's viewpoint in " My View: X Internet."

* Read Jacob Nielsen's essay about "Response Times: The Three Important Limits."

* For much more on related topics, browse the Developer Bookstore.

Source:http://www.opensourcetutorials.com
Originally Posted by Skylinux @ 2005-12-9 23:38:46

 

No Comments yet .....

 

Add Your Comment:

Note: All posts require administrator approval. Please allow 24 hours for message approval.

Name:
E-Mail:
Title
Plain text only, less then 65 000 characters.

How many times can you find the letter c in this sentence?

Please answer the question above and type the answer into the text box below.