Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

Chapter 3
Writing Your First Script

Essential Authoring Tools

In order to begin writing scripts, you need to know which text editor to use. HTML files are plain text (ASCII) files. Therefore, in order to add JavaScript to an existing HTML document, you need a text editor. You should not have any problem getting hold of a text editor for your computer.

Choosing a Text Editor

It is very important to choose the most suitable editor. The market is flooded with editors of various complexity and strength. Many text editors are also available as freeware and shareware. A simple text editor is probably the best for JavaScript programming. Most Web authors and designers use such editors because they allow plenty of freedom and enable the use of advanced features. Many different HTML editors and authoring tools are available, but you should avoid them. WYSIWYG (What You See Is What You Get) editors should not be used when adding or creating JavaScript. If you usually use a word processor that supports HTML extensions, feel free to use it. It comes in handy when you want to generate the simple HTML tags that apply to all documents. Even vi can do the job, if you know how to use it!

It is usually better to avoid powerful word processors such as Microsoft Word, because they do not deal with ASCII as a standard. However, if you do choose to use such an editor, always save your files as plain text. See Figure 3-1 for a demonstration.


Figure 3-1.  Saving an HTML document in a word processor.

Above all, it is important that you are comfortable with the text editor you choose and that it is easy to use.

The first JavaScript editing environment, Acadia Infuse, was introduced by Acadia Software. It offers an easy-to-use interface and enables fast and easy scripting. A trial version of this software is available on the CD-ROM. We discuss Acadia Infuse later in the book.

Choosing a Browser

Besides the basic programming tool, you need to be able to run your scripts and view their output. In order to run JavaScript, you need a compatible browser. Netscape Navigator 2.0x, 3.0x, and 4.0 currently support JavaScript. Microsoft Internet Explorer 3.0 and up also supports JavaScript (IE’s implementation of JavaScript is called JScript).

It doesn’t really matter which browser you choose, but using Netscape Navigator is probably the best. The Internet industry is quickly developing, so many new browsers will probably support JavaScript. When you load a local page that includes JavaScript, you do not have to be connected to the net—you can load it directly from your local disk. Overcoming JavaScript compatibility problems is often difficult, so we suggest that you have at least one version of Netscape Navigator and one version of Microsoft Internet Explorer.

Basic JavaScript Structure

In order to run client-side JavaScript, you must embed the code in the HTML document. Obviously, you cannot just place JavaScript statements in the source. There are several different ways to embed JavaScript scripts in HTML:

  • As statements and functions using the <SCRIPT> tag.
  • As event handlers using HTML tag attributes.
  • As short statements resembling URLs.

The <SCRIPT> Tag

Internal Scripts

The <SCRIPT> tag is used to enclose JavaScript code in HTML documents. Here is the general syntax:

<SCRIPT LANGUAGE="JavaScript">

[JavaScript Statements...]

</SCRIPT>

The <SCRIPT LANGUAGE="JavaScript"> tag acts like all other HTML tags. Notice that it must be followed by its closing counterpart, </SCRIPT>. Every statement you put between the two tags is interpreted as JavaScript code.

The LANGUAGE attribute is used to specify the scripting language. Although it is currently optional, you should always use it to accommodate future scripting languages. At present, the <SCRIPT> tag supports various languages including JavaScript and VBScript. JavaScript is the default scripting language, so the LANGUAGE definition is not required. When the browser comes across the precise name of the language, it loads the built-in JavaScript interpreter and then interprets the script.

JavaScript is case sensitive, but HTML is not. It does not matter whether you write <SCRIPT> or <script>, but try to be consistent. Be sure to write the name of the language properly, using capital letters where they are needed (although it does not matter to the browser).

External Scripts

Netscape Navigator 3.0 introduced a new SRC attribute for the <SCRIPT> tag, which enables the use of external scripts; that is, you can use a JavaScript script that is located in another file. This feature will eventually allow people to hide their scripts from the public, despite the fact that such action is not in keeping with the spirit of the Web. We will rarely use external scripts in the book, but remember that they exist, and you may find them helpful.

External scripts are useful when you need to integrate a long, sophisticated JavaScript script into an HTML file. This approach has several advantages:

  • Ease of maintenance. The script is isolated from outside elements, such as nonrelated HTML code. The maintenance is much easier when the script stands alone.
  • Hiding from foreign browsers. The code is automatically hidden from browsers that do not support JavaScript. The most basic rule of HTML interpretation, which enables the existence of various browsers, is that unrecognized tags are ignored (try typing <Hello> to your HTML document…). So if only the <SCRIPT LANGUAGE="JavaScript"> and </SCRIPT> tags exist, an old browser will ignore all JavaScript-related elements.
  • Library support. External scripts enable the use of JavaScript libraries, similar to the ones in C, C++, and other programming languages (e.g., #include <string.h>). You can reference general predefined functions in external scripts, thus avoiding duplication of functions or global declarations. Let’s refer once again to C++. Think of cout as a simple function you have written. You must specify the source of the function in order to use it:
    #include <iostream.h> // a directive to include the header file
    void main()
    {
      cout << "This is C++ programming"
    }
    


    JavaScript has the same structure, except that only one external file is supported.

Here are some disadvantages of using an external file:

  • No back references. As mentioned above, JavaScript scripts are mainly driven by user-initiated events. A click on a button calls a function, a selection of a form element executes another function, and so on. If you design your whole script in an external file, you will have difficulties in referring to the HTML definitions in the original file. For this reason, place only general functions in an external script.
  • Additional processing. The JavaScript interpreter evaluates all functions found in your script header, including those defined in the external file, and stores them in memory. Thus, loading unneeded functions in an external file degrades the script performance.
  • Additional server access. You know how irritating it is to wait until another page loads in the window, especially with slow modem connections. That is exactly the problem with the SRC attribute. When the browser comes across the tag which tells it to interpret JavaScript code in another file, it must first load that file. Such an action is time consuming. Most programmers say that efficiency is not as important as maintainability and clarity. However, loading a new page can cause more than the usual efficiency penalty. Always keep in mind that unnecessary HTTP hits to the server should be avoided.

Enough theory. Here is the syntax for defining an external script in the <SCRIPT> tag:

<SCRIPT LANGUAGE="JavaScript" SRC="yourFile.js">

[additional JavaScript statements...]

</SCRIPT>

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us