Previous Page TOC Next Page See Page

- 1 -
Introducing JavaScript

As discussed in the Introduction, this book assumes that you already have a working knowledge of Netscape Web publishing techniques and the use of HTML. In addition, you should also have a basic understanding of the principals behind the use of JavaScript.

However, if this is not the case, don't worry. The first section of this book is designed to provide you with all the basic JavaScript knowledge you need to understand the book's later sections.


For additional information on HTML you should refer to the HTML Guide located in Appendix B. Alternatively, "Teach Yourself Netscape Web Publishing in a Week," also by, provides a solid grounding in the many different aspects of Web publishing particular to the Netscape Navigator Web browser.

To get you started, this chapter examines the following topics:

What is JavaScript?

According to the press release made jointly by Netscape Communications and Sun Microsystems at JavaScript's launch, "JavaScript is an easy-to-use object scripting language designed for creating live online applications that link together objects and resources on both clients and servers. JavaScript is designed for use by HTML page authors and enterprise application developers to dynamically script the behavior of objects running on either a client or server."

OK, that's the official quote out of the way—what does it really mean?

The Basics

If you have ever had any contact with macros or scripting languages like Word Basic or Visual Basic for Applications—possibly in a word processor or a spreadsheet—then you already have a basic understanding of what JavaScript is all about.

In essence, JavaScript is a set of programming commands and instructions that can be used to enhance the way a Web page operates. By incorporating JavaScript commands into a Web page, you can programatically alter the way the page looks, insert or delete parts of a page's contents depending on system requirements, control the operation of a Web server, communicate with an online database, or perform any task previously associated with CGI communications. In addition, JavaScript has become the key to implementing many types of client-side interactivity, including dynamic forms that update in reaction to user input, page content programatically generated as a page loads, reacting to user events (such as clicking on links and submitting forms), and tracking user information between sessions. All of this would be impossible or extremely difficult using traditional CGI scripting.


The Common Gateway Interface (CGI) is a mechanism that enables Web publishers to programatically control the operation of a Web server and manage exchanges between the server and a Web browser using scripting languages like PERL and Bourne shell scripts. The most common use for CGI is in the handling of data and requests submitted to a Web site with Forms.

Server JavaScript and Client JavaScript

To achieve such a high level of control over the appearance of a Web page, JavaScript actually comes in two different flavors—Server Side JavaScript and Client Side JavaScript.


A server side language is one that describes programs which run on a Web server, while a client side language is one that describes programs which actually run on a Web browser.

Server Side JavaScript

With the release of the Netscape FastTrack Web Server, LiveWire, and LiveWire Pro, the JavaScript language can be used as a server side CGI replacement for the popular PERL and Bourne shell languages. Most Web publishers will already be familiar with both of these.

In the role of server side scripting language, what makes JavaScript so different from other CGI languages like PERL is the fact that JavaScript was purposefully built to be a Web scripting language. (See Part 3, "Server Side JavaScript," for more information about FastTrack, LiveWire, and Server Side JavaScript.)

While other languages, such a PERL and Bourne Shell scripts, have been used for many years as the basis for many of the complex Web sites which currently exist on the Internet, learning to use, or simply come to grips with their idiosyncrasies is—as many Web publishers discover—often a harrowing experience. Compared to such languages, writing code using Server JavaScript is a relatively straight forward task.


Throughout this book, when you see the word JavaScript used on it's own you should treat the reference as one which relates to the JavaScript language in general. On the other hand, when a comment refers to a specific version of JavaScript, the terms Client JavaScript or Server JavaScript is used.

Client Side JavaScript

Apart from acting as a CGI replacement, JavaScript's biggest claim to fame is its ability to run on a Web browser.

When JavaScript first appeared in the early beta versions of Netscape Navigator 2.0 under the name LiveScript, very few people knew exactly what to make of this new capability. Today, many Web developers have begun to develop an appreciation of the advantages client side programming can bring to a Web page.

The ability to actually generate the contents and appearance of a Web page on the fly (using a Web browser itself instead of relying on CGI programs and the sometimes limited resources available on a Web server) can lead to considerable performance benefits, as later chapters discuss in detail.


It is important to understand early on that although the two versions of JavaScript, Client side and Server side, are syntactically the same, each is designed to perform different tasks. In recognition of these differences, each is dealt with in separate sections of the book. This section—Part 1—examines the syntax and structure of the JavaScript language itself, then Part 2, "JavaScript and Netscape Navigator" explores the unique elements of client side JavaScript. Part 3, "JavaScript and LiveWire," examines the use of JavaScript in a server environment.

The JavaScript Language

The JavaScript language owes much of its heritage to the Java language developed by Sun Microsystems as a distributed Internet programming tool. In fact, much of the syntax and the command structure found in JavaScript is almost identical to that of Java. But unlike Java, which is a strongly typed language typical of the current trends in high level compiled languages, JavaScript does not demand the same level of type declaration or type checking, which Java requires.

In addition, JavaScript is—technically (more on this shortly)—not a compiled language. All compiled languages like Java, C, C++, Pascal, and earlier languages like FORTRAN and COBOL need to be run through a special program called—naturally enough—a compiler, before they can be executed. The compiler takes the English language-like commands that represent the code for a program and converts them into a form the computer can handle. This form is commonly know as a binary or executable.


To learn more about Java and how it relates to JavaScript, refer to Part 4, "Java and Live Objects."

JavaScript, on the other hand, is an interpreted language. What this means is that there is no need for JavaScript programs to be precompiled. Instead, the commands are converted into an executable form at the time the program is run—or at run-time. From the Web publisher's point of view, the fact that JavaScript is an interpreted language makes it considerably easier to program, especially when compared to the complexities and idiosyncrasies of compiled languages.


A note of caution is necessary—because JavaScript is interpreted, it's possible to generate scripts with errors and deploy them on a Web site, especially because no compiling is necessary before running the program. For this reason, it's important to thoroughly test your JavaScript applications before placing them on a publicly-accessible Web page. Otherwise, users may encounter annoying or troublesome error messages generated by Navigator in response to the errors in your scripts.


The introduction of Server JavaScript has slightly muddied the definition of JavaScript as an interpreted language. This is because when server side applications are created using JavaScript they are precompiled into what is called a bytecode format, which is not unlike a binary executable. For the moment, however, just keep in mind that the interpreted nature of JavaScript is what gives it much of its flexibility and ease of use, and this flexibility is not lost on Server JavaScript.

JavaScript Code is Embedded

What makes JavaScript so different from other languages is the unique way that it integrates itself with the World Wide Web. Instead of being stored as a separate file—like a CGI script or a Java applet—JavaScript code is included as part of a standard HTML document, just like any other HTML tags and elements.

For this reason, JavaScript is effectively an extension of the HTML language all Web publishers are familiar with. To put this in real terms, by using JavaScript you can extend, modify, or manipulate the appearance of a Web page under program based control.

Basically, JavaScript gives Web publishers the ability to create Web pages dynamically—technically the HTML code that defines how Web pages appear is written dynamically. For example, tasks such as adding the current time and date to a web page, something which previously could only be accomplished by CGI scripts or server side includes, can be easily performed using JavaScript at the time a Web page is displayed.

JavaScript is Object-Oriented

JavaScript's Java heritage also brings with it one of the most powerful design principals present in the current crop of computer languages—Object-orientated Programming (OOP).

Unlike traditional procedural languages such as Pascal and C, which define programs in terms of a top down approach, object-orientated languages define programs in term of objects and how they interact. Objects consists basically of two things—state and behavior—or to put it in more common programming terms, variables or properties, and functions which in OOP terms are called methods. (See Chapter 4, "JavaScript and Object-orientated Programming" for more information on the use of properties, methods and OOP.)

Why Would I Want to Use JavaScript?

The answer to this question depends, to a certain extent, on exactly what capabilities your Web site requires. If you currently have little or no need for CGI scripting at your site, you may find that on the surface, JavaScript seems to offer little or no benefit. Having said that, as you will soon discover, there are many ways which JavaScript can be used to enhance the capabilities of your Web site with very little effort.

If your site contains extensive CGI scripting, then what Client JavaScript enables you to do is move many simple (and not so simple) programming tasks at the Web browser (or client end) of the system, instead of relying on CGI scripts at the Web server end. In addition, Client JavaScript enables you to control with far greater efficiency the validation of information entered by users on forms and other data-entry screens, performing such task before they are ever transmitted back to a Web server. When integrated with frames, Client JavaScript brings a wide variety of new document presentation options to the Web publishing domain.

On the Server JavaScript side there are also some benefits in moving from more tradition CGI languages to an integrated, purpose designed, Web languages. There is a caveat here, however: you naturally need to have access to a Web server which supports Server JavaScript before such benefits can be obtained. Assuming that you do have access to such a Web server, the close association of Server JavaScript with the HTML pages that it relates to leads to a more streamlined approach of Web programming. (See Part 3 for more information.)

Increasing Server Efficiency

As more and more people begin to flood the World Wide Web, many popular Web sites are rapidly being pushed to the limit of their current processing capabilities. As a result, Web operators are continually looking for ways to reduce the processing requirements for their systems—to ward off the need for expensive computer upgrades.

With the introduction of Client JavaScript, some exciting new performance options are now available to Web publishers. For example, say that you have created a form people use to enter their billing details for your online ordering system. When this form is submitted, the first thing your CGI script needs to do is validate the information provided and make sure that all the appropriate fields have been filled out correctly. You need to check that a name and address have been entered, that a billing method has been selected, that credit-card details have been completed—and the list goes on.

But what happens if your CGI script discovers that some information is missing? In this case, you need to alert the user that there are problems with the submission and then ask him to edit the details and resubmit the completed form. This entire process is very resource intensive. The Web server needs to allocate a dedicated resource to perform all the validation and checks. When there are errors, two additional data transmissions must be handled by the server—one to alert the user of errors, and one to receive the updated information.

By moving the initial validation and checking procedures to the Web browser—through the use of JavaScript—you remove the need for any additional transactions, because only one "valid" transaction is ever transmitted back to the server. This simple relocation of the validation process can amount to considerable performance savings where complex forms are being submitted on a regular basis.

Due to the insidious nature of some Web users, you still need to revalidate any data submitted with a JavaScript processed form at the server to protect against the transmission of corrupted data. Unfortunately, because JavaScript code is embedded in Web pages, it is more susceptible to corruption than scripts which run exclusively on your Web server.

JavaScript and Web Service Providers

With an increasing number of Web service providers severely limiting the availability of CGI script support for security reasons, JavaScript offers an excellent method of regaining much of the missing CGI functionality. It moves tasks that would previously have been performed by a server side CGI script onto the Web browser.

Most Web service providers usually furnish some form of basic CGI script, which can take a form submitted by a user and perform basic processing operations, such as saving it to disk or mailing it to the site's owner. When it comes to more complex forms, however, in the past the only alternatives were to find another service provider or set up your own Web server. Today, with Client JavaScript, this no longer need be the case.

By using a Web service provider's basic form and processing CGI scripts with JavaScript routines buried in the Web page itself, there are very few form-based activities that cannot be duplicated on even the most restrictive and security-conscious Web service provider's site. In addition, by integrating Client and Server JavaScript together with some of the other features supported by Netscape's Web browsers, such as Java, and plug-ins, you can do things on a Web page that would never have been considered possible before with even the most capable CGI script.


Due to the secure nature of JavaScript, it is likely that in the future Web service providers may prefer to offer JavaScript CGI programming to their clients instead of access to more common languages like PERL.

Submitting Forms Without CGI

The ACTION attribute of the <FORM> tag has traditionally been associated with a CGI script located on a Web server. But, in fact, any URL can be assigned to the ACTION attribute. Doing so, however, has little value unless the resource associated with the URL can process the contents of the form in some way.


Chapter 7, "Working with Forms," provides additional information about the <FORM> tag.

That having been said, there is one type of URL—apart from a CGI script—that can process the results of a form in a meaningful way—mailto:. For example, if you included the following <FORM> tag on a page, clicking the submit button would e-mail the contents of the form to my e-mail address:


In the past, using such an ACTION could be relied upon only when the contents of the form were not vital, because there was no way to validate the information. By using JavaScript, you can now validate the data before it is e-mailed and even perform basic calculations or other processing.


Using the ACTION="mailto:email_address" option relies on the fact that the Web user has properly configured his or her Web browser to send e-mail. If this has not been done, no e-mail message is transmitted.

Why Use JavaScript Instead of Java?

Unlike Java, JavaScript is designed for non-programmers. As such, it is relatively easy to use and is far less pedantic about details such as the declaration of variable types. In addition, as mentioned previously, you do not need to compile JavaScript code before it can be used—something which you need to do with most other languages, including Java. Both Java and JavaScript have their appropriate place in the realm of Internet programming.

Java is a very powerful language which can be used to create any manner of computer or Internet applications, ranging from simple Ticker Tape displays to complex data acquisition systems and even complete Web browsers. Basically, Java lets you incorporate or program new elements into a Web page. When it comes to working with the HTML contents of a Web page itself, the difficulty involved in doing so with Java basically makes the task impossible.

It is, however, the area of HTML control where JavaScript comes to the fore. JavaScript was designed as an HTML manipulation tool which integrates seamlessly with existing Web pages. On the other hand, if you wanted to build an Internet based graphical Space Invaders game, JavaScript simply would not be appropriate to the task.

As a result, which language you use for a task in most cases comes down to the specifics of the task. If you want to control the appearance of a Web page or manage the input of data from a user, then JavaScript is the most likely choice. On the other hand, if you want to incorporate a new element or tool into a Web page, then Java is probably the tool for the job.


Because JavaScript programs and Java applets can actually communicate with each other, the two languages should not be considered as opponents of each other, but as complementary tools which can be used together. (See Chapter 15, "Communicating with Java Applets," for more information about how these two languages work together.)

The <SCRIPT> and <SERVER> Tags

As was mentioned previously, the code for JavaScript programs is embedded directly into Web pages. To accommodate the inclusion of JavaScript programs in a normal HTML document, Netscape has introduced two new tags, the <SCRIPT> tag for client side code, and the <SERVER> tag for server side code.

The <SCRIPT> Tag

By placing a <SCRIPT> tag in a document, you tell the Web browser to treat any lines of text following the tag as client side script—program code which is to be executed by the Web browser—rather than as content for the Web page. This action then continues until a corresponding </SCRIPT> tag is encountered, at which point the Web browser reverts to its usual mode of operation, treating text as Web content.

The <SCRIPT> tag may also include a LANGUAGE attribute to declare the scripting language to be used. Currently, the two possible values for this attribute are LANGUAGE="LiveScript" and LANGUAGE="JavaScript". As a rule, however, you should always use the JavaScript option because LiveScript is included only for legacy scripts, and it is doubtful whether it will be supported in future Netscape Navigator releases.


As JavaScript evolves, the use of the LANGUAGE attribute is becoming less relevant. In fact, many Web publisher no longer bother about including it in their Web pages. However, as a matter of style it is still a good idea to include it so that people have some idea about what all this strange code is doing in your Web pages.

The <SERVER> Tag

Like the <SCRIPT> tag, by placing a <SERVER> tag in a document you indicate that any lines of text following the tag are to be treated as JavaScript source code. But in the case of the <SERVER> tag the program code is to be executed by the Web server instead of the Web browser. As was the case for the <SCRIPT> tag, this action then continues until a corresponding </SERVER> tag is encountered.


Because Server JavaScript code needs to be packaged into a Web application before it can be run, it is important to note that simply putting <SERVER> tags into a Web document does not automatically start any programs running on a Web server.

The Structure of a JavaScript Script

When you include any JavaScript code in an HTML document, apart from using the <SCRIPT> or <SERVER> tags, you should also follow a few other conventions:

Unlike HTML, which uses the <!-- comment tag -->, comments inside JavaScript code use the // symbol. Any line of JavaScript code that starts with this symbol is treated as a comment and ignored.

Taking these three points into consideration, the basic structure for including JavaScript code inside an HTML document looks something like the following:

<TITLE>Test script</TITLE>
<!-- Use the start of a comment tag to hide the JavaScript code
  Your JavaScript code goes here
// close the comment tag on the line immediately before the </SCRIPT> tag --!>
   Your Web document goes here

The SRC Attribute

Besides the LANGUAGE attribute, the <SCRIPT> tag also can include a SRC attribute. Including an SRC attribute enables a JavaScript script stored in a separate file to be included as part of the current Web page. This is a handy option if you have several Web pages that all use the same JavaScript code and you don't want to type the scripts separately into each page.

When used like this, the <SCRIPT> tag takes the following form:

<SCRIPT LANGUAGE="JavaScript" SRC="http://script.js">

In this form, script can be any relative or absolute URL, and .js is the file extension for a JavaScript file.

One of the most important uses for the SRC attribute is the creation of what are called Code libraries. As you begin to work with JavaScript you will often find yourself including code in one page that needs to appear on others. By using the SRC attribute, you can write the code once and store it as a separate file. When you need access to the code, simply append it to the pages where you need it by using the SRC attribute.

The Development Environment

Because all JavaScript code is simply a part of an HTML document, you don't need to use any special tools to create your JavaScript programs. If you currently have a HTML editor or text editor (see figure 1.1) which you are happy using, then for the most part you probably don't need any other tools.

Figure 1.1 Any text editor can be used to write JavaScript code.

Netscape GOLD

If, on the other hand, you are currently looking for a tool to assist you with your Web publishing needs, then the Netscape Navigator Gold program would be well worth a look. Apart from being a Web browser, Navigator Gold is also a HTML editor. See figure 1.2.

Figure 1.2 Netscape Navigator Gold is both a Web browser and a HTML editor.

By integrating the Web browsing capabilities of Netscape Navigator with an HTML editor, Netscape Communications have created a program which can assist greatly in the streamlining of your Web publishing tasks.


To learn more about Netscape Navigator Gold refer to Appendix A, "Netscape Navigator and Netscape Gold."


For those readers who plan to make use of the capabilities provided by Server JavaScript, there is one additional program which you need to become familiar with.

As mentioned previously, Server JavaScript code needs to be precompiled into a Web application before it can be run on a Web server. To compile a Web application you need to have access to the Netscape Site Manager application shown in figure 1.3.

Figure 1.3 Netscape Site Manager lets you manage all aspects of your web site.

Site Manager, which is a part of the LiveWire server extensions, lets you manage the layout and content of your Web site. It also includes the tools required to compile your Server JavaScript code into a Web application so that it can be executed correctly by a Netscape Web server.


JavaScript is an object based scripting language designed by Netscape Communications specifically for manipulating and managing the contents of Web pages. JavaScript programs can be run either on a Web server or Web browser depending upon your particular needs and requirements.

The most significant feature of JavaScript, and the one which separates it from other scripting languages, is the way that JavaScript code is physically embedded into a Web page instead of being stored in a stand alone file. This integration, and JavaScript's ability to modify and manipulate the contents of a Web page dynamically, make it ideally suited to even the most complex Web publishing needs.

Previous Page Page Top TOC Next Page See Page