Archives
 
 
 
  Special
 
 
 
  About Us
 
 
 

Newsletter
Free E-mail Newsletter from BYTE.com

 
    
           
Visit the home page Browse the four-year online archive Download platform-neutral CPU/FPU benchmarks Find information for advertisers, authors, vendors, subscribers

ArticlesWriting JavaScript Applications


February 1998 / Core Technologies / Writing JavaScript Applications

A look at several basic tricks necessary to write application-caliber programs using JavaScript.

Bob Friesenhahn

On September 12, 1997, an industry newspaper reported that Microsoft is giving Java applets "the boot" on its Web site. Clearly something is afoot at the company that cared enough about Java to write its own Java interpreter rather than use one licensed from Sun. Some reports have it that this "something" is JavaScript. For most Web browser uses, JavaScript loads faster, runs faster, and produces pages that are more "Web-like" than equivalent Java appl ets.

Traditionally, Java has been seen as the language for writing browser-based applications. However, JavaScript implementations have reached a level of sophistication and stability so that JavaScript can be used to write useful applications. Since JavaScript is much more closely wedded to the fabric of the browser, applications can be written in fewer lines of code. This smaller code footprint consumes less processing power and fewer network resources than Java.

JavaScript Basics

What is meant by the term "application?" For the purpose of this article, an application is code that executes in the client and enables calculation, presentation, manipulation, and saving of results (with minimal interaction) to a server. An application may manipulate complex data structures and display multiple screens of output without requesting new pages from the server.

JavaScript provides many capabilities that are useful to support browser-based applications. These include:

  • general-purpose computations
  • general-purpose data structures (strings, arrays, and hashes)
  • dynamic HTML-based content generated on the fly
  • data loaded as JavaScript
  • interval timers

Note that JavaScript does not provide any support for graphics capabilities beyond those provided by HTML. This is a key point: JavaScript must leverage the capabilities of the browser and HTML to display content. Other than a few dialog-box functions, JavaScript provides no direct display capabilities.

JavaScript is no panacea. It has characteristics that work against developing full-fledged applications. For example, it has severely limited communications (read-mostly) with a server and severely limited means of storage. Unlike most languages, there's no global variable and function namespace available. In addition, JavaScript relies on a complex browser object model, and there's no protection from external manipulation by the browser. Until recently, JavaScript lacked a standard, which resulted in some implementations of patchy quality. Fortunately, this is changing: The European Computer Manufacturers Association has developed a specification for JavaScript, known as ECMA-262 (or ECMAScript). For more information, you can download the standard at http://www.ecma.ch/ .

Due to the limitations of JavaScript, developing a JavaScript-based application is like preparing for battle. The developer must be aware of JavaScript's strengths, as well as its weaknesses. He must also know the environment in which the application will be used. The first step in developing a JavaScript application is to identify who will be using it. The users must be running browsers that support a reasonably current version (at least 1.1) of JavaScript. It is unwise to completely abandon the (usually vocal) minority in favor of the majority. While JavaScript can improve performance and access for browsers that support it, some other means (e.g., HTML pages or a CGI script) should be made available to support less capable browsers. Careful use of <SCRIPT> tags and the window.location.href property can shunt JavaScript users to special pages just for them while providing existing HTML pages for other people.

Window Tricks

As mentioned earlier, JavaScript associates variables and functions with the windows they are defined in. There are no global variables in JavaScript. If the HTML in a window reloads, all the pre-existing variables and functions in that window get erased. This effect is the single greatest hurdle to overcome in order to move JavaScript beyond simple dynamic pages into the realm of a full-fledged application. The key is to create a window that remains constant throughout the application's lifetime. You do this by defining a window with static content (and that can't b e resized) or by creating a (usually) hidden zero-size window. Place all variables and functions that define the core of your application in this stable window, as shown in "Maintaining a JavaScript Application's State."

Since your application is subject to the whim of the user, make sure that the window you choose for storage won't be deleted by making it obvious that this is the application's main window. Ensure that your JavaScript application handles unexpected events properly. If multiple windows are in use, supply a window.onUnload() handler that closes any child windows if the user does the unthinkable and deletes the main window. Since windows can be loaded in any order, and the user might start using windows before they (or windows they depend on) are fully loaded, consider adding an onLoad handler to FRAMESET definitions to let you know when all windows have been loaded. Practice defensive coding by testing to verify that windows, frames, variables, and functions exist before attempting to use them. It is usually best to ignore inputs until all the windows of the application are loaded and initialized.

JavaScript has a severe limitation: It can load data only by loading a URL into a window. At first glance, this would seem to make JavaScript totally unsuitable for writing any kind of application. However, the URL that loads can contain JavaScript that defines things such as simple variables, arrays, and hashes. Once these variables load into a window, they can be accessed by other windows. Browsers that support JavaScript 1.1 or later can load JavaScript source files directly via the syntax <SCRIPT LANGUAGE="JavaScript1.1"SRC="data.js"> . Multiple statements of this kind can occur in a single HTML file. The effect is additive, so one source file may define JavaScript functions, while other source files define data. If the data the application requires is static, it may be loaded from a pregenerated HTML file. If the data is dynamic, the referenced URL can be a CGI script that returns data (and possibly additional functions) formatted as JavaScript source code.

Cookies and Forms

The only means that JavaScript has for saving state are local JavaScript cookies and HTML form submissions. Cookies are best used for keeping track of user information between sessions. Forms are best for submitting final data to a CGI application on the server where results are stored. If you want to add Java to the mix, versions of Netscape Communicator 3.0 or later support the ability to communicate between JavaScript and Java. Since Java communicates efficiently with the server, it can be used as a bridge between JavaScript and the server.

JavaScript is a complex language that you cannot learn in one sitting. As the inventor of JavaScript, Netscape is the authority on JavaScript syntax. The company maintains JavaScript documentation on its developer support site at http://developer.netscape.com . A book I have found to be an outstanding reference is David Flanagan's JavaScript: The Definitive Guide, 2nd Edition , published by O'Reilly & Associates.


Three Ways to Slice It

JavaScript applications depend on dynamically generating HTML. The
following code fragments illustrate three different ways to write
HTML from a window named "main" to an adjacent window named "output."
The function Text() below returns the desired HTML.

function Text() {

 var htmlText =
  '<HTML><HEAD>\n' +
  '<TITLE>Hello World</TITLE><HEAD>\n' +
  '<BODY><H1>Hello World</H1></BODY>\n' +
  '</HTML>\n';
 return htmlText;
}


First method:
 Open and write to window directly.

parent.output.document.open('text/html');
pa
rent.output.document.write(Text());
parent.output.document.close();


Second method:
 Open window and write to its document object.

var out = window.open(", 'output');
out.document.write(Text());
out.document.close();


Third method:
 Open window using a JavaScript URL.

window.open('javascript:parent.main.Text();',
  'output');



Maintaining a JavaScript Application's State

illustration_link (18 Kbytes)

You can store application functions and preserve variables in a window with static content.


Bob Friesenhahn ( bfriesen@simple.dallas.tx.us ), a f requent contributor to BYTE, specializes in Unix and TCP/IP networking topics.

Up to the Core Technologies section contentsGo to previous article:
Flexible C++
Matthew Wilson
My approach to software engineering is far more pragmatic than it is theoretical--and no language better exemplifies this than C++.

more...

BYTE Digest

BYTE Digest editors every month analyze and evaluate the best articles from Information Week, EE Times, Dr. Dobb's Journal, Network Computing, Sys Admin, and dozens of other CMP publications—bringing you critical news and information about wireless communication, computer security, software development, embedded systems, and more!

Find out more

BYTE.com Store

BYTE CD-ROM
NOW, on one CD-ROM, you can instantly access more than 8 years of BYTE.
 
The Best of BYTE Volume 1: Programming Languages
The Best of BYTE
Volume 1: Programming Languages
In this issue of Best of BYTE, we bring together some of the leading programming language designers and implementors...

Copyright © 2005 CMP Media LLC, Privacy Policy, Your California Privacy rights, Terms of Service
Site comments: webmaster@byte.com
SDMG Web Sites: BYTE.com, C/C++ Users Journal, Dr. Dobb's Journal, MSDN Magazine, New Architect, SD Expo, SD Magazine, Sys Admin, The Perl Journal, UnixReview.com, Windows Developer Network