Chapter 1 What Is JavaScript to a Programmer?

In the beginning, there were Assembly and compiled languages. Later came scripting languages such as sed, awk, and Perl, which many programmers used to perform a variety of tasks. Followed by, in the late 80s and early 90s, the Internet, which exploded into a technological revolution that allowed anyone with a modem to communicate and retrieve information from around the world. As the Internet grew in number of users, it was obvious that an increase in functionality was needed in the browsers and the data they were rendering.

HTML, even with its advantages, was falling short of providing the control many developers wanted when creating Web pages and applications. This prompted the use of server-side programs, or scripts as they were often called, to handle some of the page dynamics developers needed from their sites.

These programs helped Web developers by allowing them to increase a site’s functionality as well as process user-submitted information. However, CGI, or common gateway interface, scripts had to generate and return a response when the user sent incorrect or incomplete information. This led to the unnecessary back-and-forth transmission of data between browser and server. But, overall, it was a minor price to pay for the functionality it provided.

With time, and an increase in traffic, it became increasingly obvious that client-side intelligence was needed to offload some of the CGI functionality. Something was needed to perform this error checking and to decrease the amount of time a user spent connecting to a server to validate data. This would also enable the Web site to offload some of its processing load to the browser machine, which meant an increase in the overall performance of a site.

It was partially this lack of client-side functionality and efficiency that helped spawn a new scripting language—one that could be executed within a browser’s environment and not on the server. This language could be used to perform client-side tasks such as form validation and dynamic page content creation—one that would put the programming into HTML publishing. Welcome to the birth of JavaScript.

Welcome to JavaScript

On December 4, 1995, Netscape and Sun jointly introduced JavaScript 1.0, originally called LiveScript, to the world. This language, unlike its server-based predecessors, could be interpreted within the then new Netscape Navigator 2 browsers. As an interpreted language, JavaScript was positioned as a complement to Java and would allow Web developers to create and deploy custom applications across the enterprise and Internet alike. JavaScript gave Web developers the power to truly program—not just format data with HTML.

In addition to the client-side control developers desired, Netscape implemented server-side JavaScript. This allowed developers to use the same programming language on the server as they did in their pages for browsers. Database connection enhancements were added to the language (called LiveWire), allowing the developer to pull information directly from a database and maintain user sessions for common functionality such as shopping carts. JavaScript had truly bridged the gap between the simple world of HTML and the more complex CGI programs on the server. It provided a common language for Web developers to design, implement, and deploy solutions across their networks and distributed the overall processing load of their applications.

The next level of acceptance in the world of JavaScript was Microsoft’s implementation of the language in its Internet Explorer 3 browser—the implementation was called JScript. Similar to Netscape, Microsoft also implemented the language on the server-side (JScript 2.0) within its ASP (Active Server Pages) environment. It also allowed developers the flexibility of using a common language on both the client and server-side, while providing many of the robust features, such as object invocation and usage, in compiled languages.

So, what is JavaScript to the programmer? Well, in its purest form, it is an object-based, cross-platform, loosely-typed, multi-use language that allows a programmer to deploy many types of solutions to many clients. It not only involves adding functionality to Web pages as rendered within a browser, it also allows server-side processing for Netscape and Microsoft Web servers.

JScript has also been included in Microsoft’s Windows Script Host (WSH), to allow programmers to write scripts to be executed on the operating system itself, and most recently as a major language under their .NET strategy (more on that later). When operating within the WSH environment, JScript is similar to the old DOS batch files, but gives programmers more functionality and versatility in what they can accomplish. This type of advancement has allowed the language to take hold in the computer world and continue to progress.

In addition to the benefits of these environments in which JavaScript can be executed, security measures are in place to protect end users against malicious code. Even though it is still young in terms of age, JavaScript is very mature and powerful. This functionality, ability, and versatility positions JavaScript as the best solution for many programmers.

Now that you’ve learned about what JavaScript is, you should dive a little deeper into what it means to a programmer. Being programmers ourselves, we know that a few strategically placed words do not make a language useful; so first, we’ll look at the object-based characteristics of JavaScript.

Object-Based Technology

The fact that you are reading this reference somewhat implies that you have programmed in JavaScript or at least one other language before, even if only for one semester in college. Going one step further, I bet the language you programmed in was either C++, Java, or Perl—with each having various levels of object orientation (OO). Java specifically is OO by virtue of having all programmer created objects extend from core Java language classes or their own.

Object-Oriented Programming

For those of you unfamiliar with object-oriented programming (OOP), it is a concept that allows you to create reusable objects or classes in code. An object or class has associated with it various characteristics and functionality that defines what kind of properties and states it can take on. After these are created and defined, it is possible to create new instances—sometimes referred to as children—that inherit the capability to have the same characteristics of their parent object.

To give you an example of how this might work, let’s create a vehicle object. Some of the characteristics assigned to this vehicle object are the number of doors, the color, and the type (such as sports car or truck). In addition to these characteristics, let’s define the ability to move or stop the vehicle. The pseudo-code for this type of object might look something similar to the following:

object vehicle(){
  // Characteristics of the vehicle
  num_doors;
  color;
  type;

  // Methods used to move and stop the truck. Note that the move()
  // method takes a direction as an argument. This direction could
  // be something like forward, backward, left, or right.
 move(direction);
  stop();
}

Now that this vehicle object is defined, it is easy to create new instances of it. A vehicle that is a car with four doors and is red can be easily created. You could also create a vehicle that is a truck with two doors and is black. The possibilities are endless.

In addition to creating these instances of the vehicle object, you have also made it possible to program in the ability to change the state of your instance. This is accomplished by specifying whether it is stopped or moving. Again, this method of programming can make the possibilities endless and certainly reusable.

Here is another example in pseudo-code to illustrate this concept. The sample creates a black, two-door truck that is moving forward:

//  Create   the   new instance of the vehicle
myTruck = new vehicle();

//  Define   the  type, number of doors and color
myTruck.doors = 2;
myTruck.color = “black”;
myTruck.type = “truck”;

//   Define   the    “state” of the truck
myTruck.move(forward);

The basic process here is to create an instance of the vehicle object and then to assign characteristic values to it. It is these values that make it a unique instance of this object, which we have specified as a truck.

The existence of the vehicle object itself allows us to easily create more vehicles with different characteristics. When programming, this “ease” translates into less code—something all programmers like to hear.

Now that this object is defined, it is possible to create new instances that inherit its characteristics without having to redefine them. You are able to capitalize on any overlaps in characteristics within objects by doing this. The idea is to create a general, master object that gives you the ability to then derive child instances that provide all the functionality and characteristics you need.

We can take this a step further by creating new objects—not instances—that inherit the parent objects’ characteristics. Doing so allows us to derive child instances from the child object that we have decided will inherit only certain characteristics. We could define a child object to only pass on the parent object’s color characteristic to any child instances of its own. It is the concept of this object orientation that allows you to perform this modular type of programming.

The following pseudo-code example shows how we could create an airplane object based on the previous vehicle object:

//  Create the new object that inherits the vehicle
object airplane(){

  // Inherit   the  vehicle  object
  this = new vehicle();

  //  Define  the  doors property,   then  assign  it  to  the  size
  //  property  of  the  plane  object, which  makes the most sense
  this.doors =  “747”;
  this.size =  this.doors;

  //  Assign  the  color  and  type of  plane
  this.color = “silver”;
  this.type = “American Airlines”;

  // Define the “state” of the plane
  this.move(up);

  // Now that the object is created with the values, return the
  // object.
  return this;
}

Not all languages support this concept, and there are other languages only based on its concepts. This concept definitely supplies advantages to the language, but it is not required to write good, effective, modular code. JavaScript is a perfect example of how a language has applied some of these concepts, but is not completely OO. It does this by being object based.

So how does object-based programming fit into the equation? It is very similar to OO except that it does not have all the functionality or characteristics. There are limited amounts of inheritance, scope, and functionality that you can perform with an object-based language. This should not be taken as mark against JavaScript, because it makes the language easier to learn and maintain for the developer. OOP is no easy beast to tackle and will provide many headaches before it is implemented correctly.

JavaScript also makes up for many of its OO limitations by allowing you to create your own object-like elements, as well as extend the core objects in the language by prototyping new properties. To get an idea of how this is done, take a look at JavaScript object orientation.

Object Orientation of JavaScript

Before we go into a lot of detail on the object orientation of JavaScript, let’s outline the details of the core components as well as between server-side and client-side objects. Both sets of objects are specific to their runtime environment, so default object initialization and creation occur at different times. Because of this characteristic, you will look at the language in several parts:

• Core

• Client-side

• Server-side

• JScript-specific

• Windows Script Host

Core

First and foremost, it is important for you to know and understand the core objects in the JavaScript language. These objects are generally found across all implementations and are defined in the ECMAScript standard. These objects lay the foundation for the shared functionality, such as mathematical, array, or date related, which are used in most all scripts. Figure 1.1 shows a list of these core objects.

Figure 1.1 Core ECMAScript object hierarchy.

Image

As you can see, the core objects are Array, Boolean, Date, Function, Global, Math, Number, Object, RegExp, Error, and String. In addition to these objects, both Netscape and Microsoft have created objects specific to their core implementations. These are not specific to any environment, and are therefore core objects in the sense of their consistency. Figure 1.2 shows these objects.

Figure 1.2 Core object hierarchy for Microsoft and Netscape environments.

Image

Client-Side

Client-side JavaScript is, at its lowest level, a set of objects created when a page is loaded in the browser. In addition, there are also objects that revolve around the browser loading the page and other derived objects that are created when certain tags are contained on a page. These derived objects inherit some of the various characteristics of their parent object and also allow scripting access to the HTML tag’s properties.

Understanding the hierarchy of the JavaScript objects is essential if you plan on doing any in-depth programming. You will get a better understanding of how parent and child objects interact as well as how they are referenced. To help with this understanding, Figure 1.3 gives a graphical representation of the basic client-side JavaScript hierarchy.

Figure 1.3 Client-side JavaScript object hierarchy.

Image

As depicted in this diagram, all client-side objects are derived from either the Window or navigator objects. Considering that this is an object-based language, this structure makes complete sense. All objects on a given page are constructed within the browser’s displaying window, hence all these objects are descendants of the Window object. By using the Window object, a programmer is allowed to access the various frames, documents, layers, and forms on a page, as well as many other objects and properties.

The navigator object pertains to elements that are part of the browser itself. This specifically refers to the plug-ins installed and the MIME (Multipart Internet Mail Extension) types with which the browser is associated. Using the navigator object allows checking of the browser version, determining the plug-ins installed, and what programs are associated with the various MIME types registered on the system. There is also the ability to access other properties of the browser.

In addition to these client-side objects, browsers starting with Internet Explorer 5 and Netscape 6 have implemented features to support the Document Object Model (DOM). The DOM is a method in which documents can be referenced. We talk more about the DOM in Chapter 4, “Client-Side Scripting,” but wanted to include Figure 1.4 to show you the objects that make up this model.

Figure 1.4 DOM object hierarchy.

Image

Server-Side

Similar to client-side, server-side JavaScript has several objects from which all other objects are derived. The root objects are the DbPool and database objects, for the Netscape and iPlanet implementations, from which you can create connections to a database, as well as access cursors, stored procedures, and the resultsets you generate. Within the Microsoft ASP environment, you have access to several other objects, such as Response, Session, and Request. Figure 1.5 shows the server-side objecthierarchy.

Figure 1.5 Server-side object hierarchy.

Image

JScript Runtime

As with about every other language that Microsoft has put its hands on, its JScript implementation contains objects that are specific to their runtime environment. Because their JScript engine is used within several of their applications and is a very important part of their .NET initiative, you will notice that many of the additional objects are familiar if you have ever worked with COM. Figure 1.6 illustrates the objects that are specific to the JScript implementation.

Figure 1.6 JScript RunTime object hierarchy.

Image

Windows Script Host

In addition to the JScript-specific objects, Microsoft has also implemented objects that are part of its Windows Script Host environment. These objects, and associated code, are often used by administrators to perform everyday tasks previously done with batch files. The Windows Script Host, however, is much more powerful than the batch files of yesterday, and should be seriously considered for your administrative tasks. Figure 1.7 outlines the object hierarchy of the Windows Script Hostobjects.

Figure 1.7 Windows Script Host object hierarchy.

Image

Object Access

Because of this object hierarchy, accessing the various objects and elements on a page is accomplished by using the hierarchy itself. If you wanted to access a specific text field in a form on a page, you would do so using the following syntax:

window.document.formName.textboxName.value

Because JavaScript is object based, it automatically provides many advantages to using a modular approach to your programming. By creating your own objects and methods, you are able to better maintain the code with which you are working. You will be creating code that can be reused in other programs, locations, and instances. Why write virtually the same code twice (or many times), when you can create it once and pass the characteristics that differentiate it from other, similar objects?

Modular Programming

To program in a modular fashion in JavaScript really involves three key things. Using these items in your programming will allow you to create code that can be reused from project to project. These are

• Creating your own objects

• Defining general functions to handle common tasks

• Placing reusable code in external JavaScript source files (commonly *.js files)

Because creating your own objects is discussed in Chapter 2, let’s take a look at defining functions to handle common tasks. As with other programming languages, there are instances in which you have to perform certain processes over and over. Many times this might involve a different value of parameters passed, but the processes you go through are the same.

As an example, think of verifying a date entered by a user. This user is supposed to enter the month, date, and year in a form that will be submitted to your Web server for further processing. One of the concerns of the programmer is that he needs to have the date in a MM/DD/YYYY format, where the month and date need to be two characters and the year should be four.

To accomplish this task, you can create a single function that prepends a 0 in front of any single digit passed. This function could simply check to see if the value passed was less than the number 10, and, if so, it would perform the prepend. By defining this process in a function, a programmer will be able to use the same function for both the month and date verification. This avoids the trouble of writing a function for each. Even though this is a simple example, it illustrates the benefits of function and code reuse.

Programmers can also modularize their programming techniques by including their code in external JavaScript source files. This allows them to write code once, store it in a single location, and include it on many pages by simply referencing the location of the source file. If the function needs to change, they only have to change it in a single file and not every file that uses it. It is simple things such as these that save Web programmers hours or days of work time.

Security

One of the biggest issues facing Internet development today is security. It is not possible to successfully develop any kind of application, whether it’s Web based or based on the Web, and not have to implement some kind of security features. A program’s security measures can ultimately determine how valuable the overall application is to a user. If the code can be tampered with or is subject to destruction from another program, the program will be subject to scrutiny and denial of use.

Because JavaScript is interpreted most often within a browser’s environment, a user can be subject to malicious code. Browser’s run off the operating system itself, meaning that it has access to a user’s file system. This makes it feasible that a JavaScript program could take advantage of a hole in the browser’s security measures to access the file system. After a programmer has accomplished this, many things are possible—even access to private documents or the ability to delete them altogether. This leaves a user at the mercy of a hacker.

Providing security for JavaScript scripts is actually twofold. One is that of responsibility, which lies with the programmer. A programmer must ensure that the script the user executes is not malicious. The second responsibility falls to the users themselves. Users should make the ultimate decision whether to run a script on their systems—this is something that must be implemented in the browser’s functionality.

Because of these potentially destructive situations, there are various levels of security that users and programmers can rely on when programming in JavaScript. As discussed, some are the responsibility of the programmer, whereas others involve measures put in place by the browser that allow the user to control what is executed on his system.

What Security Measures Are in Place?

When JavaScript 1.0 was released in the Navigator 2.0, Internet Explorer 3.0 (JScript 1.0), and Opera 3.0 browsers, the only real security layer was that of a user having the ability to turn JavaScript on or off. The browser itself controlled the runtime environment for the language and any security measures it had in place.

In this model, when JavaScript was enabled, it was up to the browser to protect the user from any harmful code. Originally, this seemed like a thorough plan for implementing security. Leave it to the experts to protect the users. However, where there is a will there is a way, and the first misuses of JavaScript began to surface.

One of the first items that seemed to be a potential problem occurred when frames were used on a Web site. Because frames load separate documents in each of the predefined areas, it is possible to load documents from several different domains and servers to make up the content displayed to the user. The problem arose when a document’s JavaScript variables from one server were available for examination and modification on another. But this was only the start of the potential security holes that would follow.

To help protect users from the frame problem, Navigator 2, Internet Explorer 3, and Opera 3 implemented the Same Origin Policy. This policy prevented JavaScript code sent from one server from accessing properties of a document sent from another server, port, or protocol and returning that information to its original server.

Obviously, this policy does not affect all the elements of a given document, but it does include a core set. At the time of this printing, the document properties that must pass this origin check are in Table 1.1.

Table 1.1 Document Objects That Must Pass Origin Verification

Image

Because it might be desirable for a script to access variables located on a page served from another server within the same domain, there is an exception to this security model. By definition, it would not be possible to access and upload document properties in a frame served from http://myscripts.purejavascript.com from another frame that was delivered from http://mydocs.purejavascript.com. Even though the domain is the same, the complete URL is not.

To get around this minor situation, programmers can set the document.domain property to the suffix of the current domain. This will allow them to access JavaScript properties on pages served from other servers within their domain. Following the example in the last paragraph, using the following line in the code can enable this feature:

document.domain = “purejavascript.com”;

Setting this property will allow you to access the other sub-domains within your domain.

Data Tainting

When JavaScript 1.1 was released in Navigator 3.0, Netscape furthered its security implementation by using what is referred to as data tainting. In addition to the security model in the first generation JavaScript browsers, data tainting allowed the user and programmer to specify if they wanted scripts to access properties in other documents from other servers. When data tainting is not enabled, which is the default, the user will get a message saying that accessing document properties from other servers is not allowed.

Users can enable tainting if they want scripts on a page to have global access to other scripts and document properties. This is a security risk, but might be necessary within an enterprise environment in which other security measures are in place. To enable data tainting, environment variables must be set for the browser running the scripts. Table 1.2 shows how this can be accomplished on the various operating systems.

Table 1.2 How to Enable Data Tainting for Your Navigator Browser

Image

After this variable is set, a number of document properties are affected. Table 1.3 shows a list of the document objects that are tainted by default.

Table 1.3 Document Objects That Are Tainted by Default

Image

In addition to the user having the ability to specify how he wants to handle tainting, a programmer can specify, or taint, objects or information that cannot be passed from one script to the next without the user’s permission. When this occurs, the browser will pop up a dialog box that allows the user to decide whether the information can be passed.

Because data tainting did not provide the true security model JavaScript needed, Netscape deprecated its functionality in JavaScript 1.2 and replaced it with Signed Scripts. This is the current and most complete model that has been implemented, and should be used by JavaScript developer’s moving forward.

Signed Scripts

Signed scripts allow a programmer the ability to gain access, after user authorization, to restricted information. This model, which was based on the signed objects model in Java, uses LiveConnect and the Java Capabilities API to execute its functionality. Using this model gives programmers very defined control over what they can and cannot do on a user’s machine.

When using this model, you have the ability to sign external JavaScript source files (called through the src attribute of the <script> tag), event handlers, and code that is included inline on the page. The actual signing of these scripts is implemented by using Netscape’s Page Signer tool, which is available at http://developer.netscape.com.

This Page Signer tool allows you to build a JAR (Java Archive) file that includes the programmer’s security certificate and code. When the browser encounters a <script> tag that has an archive attribute set, it will go through the proper verification process before the script is executed. This process involves popping up a Java Security dialog box that gives the user the ability to grant or deny the rights to the script. The following is an example of syntax used on a page that includes a signed script:

<script src=“myScripts.js” archive=“sample.jar”></script>

If the code is inline, the JAR file will contain only the programmer’s certificate. Calling the appropriate JAR file would then resemble the following, which does not have the src attribute, and it would have the code between the beginning and ending <script> tags.

<script archive=“sample.jar” id=“purejs”>
// Your code here
</script>

Even though signed scripts are based on a Java model, there are enough differences in the languages that make it a bit harder to secure JavaScript code. Unlike JavaScript, a Java programmer can protect, make private, or make final variables and methods in their code. This inherently protects them from hackers because these elements cannot be accessed or changed—the Java language defines them as such.

Some expanded privileges can be accessed through the netscape. security.PrivilegeManager.enablePrivilege() method, which gives more control in scripting. This Java method allows a programmer to try to enable one of a set of privileges by asking the user to accept or reject his access. As with other signed scripts, this will prompt the user to grant or deny a programmer’s request. The following list shows the privileges that a programmer can attempt to access for these purposes:

UniversalBrowserAccess—Allows both reading and writing of privileged data in browser.

UniversalBrowserRead—Allows the reading of privileged data in browser. This is required when using an about: (but not about:blank), getting any property of the history object, or getting the value of the data property of a DragDrop event within your scripts.

UniversalBrowserWrite—Allows the writing of privileged data in browser. This is required when setting any property of an event object, adding or removing any of the browser’s bars (location, menu, status, and so on), as well as using several of the methods and setting some of the properties of the Window object within your scripts.

UniversalFileRead—Allows the script to read files on the file system of the machine on which it is running. This is required when using a file upload within your scripts.

UniversalPreferencesRead—Allows the script to read browser preference settings.

UniversalPreferencesWrite—Allows the script to write browser preference settings.

UniversalSendMail—Allows the script to send mail under the user’s name. This is required when using a news: or mailto: within your scripts.

JavaScript has quite an extensive list of security measures in place that can be used by the programmer. However, a programmer should use the security measures in a manner that maximizes his effectiveness. If this is not done, the scripts are subject to hacking.

Now that you have an understanding of the security measures in place for JavaScript, take a look at some of the overall advantages of using the language as a means of deploying solutions on the Internet or within an enterprise.

Advantages of JavaScript

Up to this point, you might not have seen any big reasons where and why JavaScript can help you. It is object based, can be interpreted within a browser, and there are security measures in place—but the same can be said for Java. Now that browsers support plug-ins and ActiveX controls, it is possible to design client-side functionality with more common languages such as C++ or Visual Basic. So what does JavaScript really give you?

For starters, it is platform independent. This is a major advantage over ActiveX controls and plug-ins because they have to be recompiled and potentially rewritten for the various platforms out there today. Previous versions of Navigator and the new Netscape 6, for example, run on many different platforms, and even though most of these are various flavors of Unix, at its core, you would still have to build a control or plug-in for Windows 16- and 32-bit systems, MacOS, Unix, BeOS, OS/2, and the list goes on. Also note that flavors of Unix and Linux can run on several types of processors (MIPS, Intel, PowerPC, and so on), and Windows NT runs on Intel and Alpha machines. This becomes quite an extensive list of components to maintain if you develop in a platform-dependant language.

Another advantage of JavaScript is that both Netscape and Microsoft Web servers have built-in interpreters. Both of these companies have implemented this in a different fashion, but, as a Web developer, you still have the ability to use the same language on the server-side that you do on the client-side. The only real competitor to JavaScript in this aspect is Java with its Java applet and servlet technology.

Platform Independence

Platform independence is probably the number one reason to use JavaScript within your applications. True, some environments interpret JavaScript a bit differently, but the majority of the language is processed the same. The code is interpreted so that you can write it once and let the execution environment interpret it.

This is a simple concept, but can be a big factor in deciding how to implement an application solution. As a programmer, you do not want to have to modify code to work on different operating systems or recompile for different microprocessors. You want to write the code once and be done with it. You want to be able to make changes easily and quickly without having to recompile 10 or 15 times. Let’s face it; you want and need JavaScript.

Client-Side and Server-Side Versatility

The majority of the discussion so far has focused on using JavaScript on the client-side. Even with its initial release, JavaScript has also been implemented on the server-side within the Netscape/iPlanet and Microsoft Web servers. This server-side code contains many of the same objects and methods as the client-side, but it also has objects specific to the server environment—objects that allow you to connect to, query, and get results from a database. All this information is collected and processed before the server sends the page back to the requesting browser.

By providing this scripting capability on the server, a programmer can now use the language to dynamically build pages based on the execution of the server-side scripts it contains. Server-side JavaScript also can be used to maintain state for users as they move through a site. This maintaining of state is often implemented as a shopping cart on commercial sites. As users shop on a given site, server-side JavaScript can be used to track them and keep selected items in their carts.

Microsoft has also implemented a type of server-side JScript within its Internet Information Server (IIS). Its implementation is used in Active Server Pages (ASP), where the ASP filter parses a site’s pages before they are sent back to the requesting browser. JScript is also a very important language within Microsoft’s .NET initiative, where developers can use the language to create Web services that operate much the same as COM objects, but across the Internet. As with Netscape’s implementation, this allows a Web developer to dynamically build the content of a page before it is sent back to the browser.

Because of the functionality of these pages, ASP has given developers the ability to use JScript to call server-side components (such as ActiveX controls), pass the necessary parameters, and write the results to the screen. This allows a Web site to modularize all the functionality of building pages with individual components that are responsible for their specific tasks. JScript is used to handle the requests and results to and from these modules, and then write the results to the page.

When to Use JavaScript

One of the most important things to know about JavaScript is when to use it. Even though it provides much needed functionality in many scenarios, often it is simply not needed. One reason is the fact that JavaScript is not always interpreted the same or correctly—an important point to remember.

As a programmer, you should be able to write code, no matter how simple or complex, that will be executed correctly. However, there are browsers that have bugs that prevent JavaScript from working the way it was programmed. Before programming in JavaScript, you should first try to understand any documented bugs that exist. Doing so can save you hours of debugging in the long run. You can often find these bug lists on the Web, so check out our resource section toward the end of this chapter to get started.

Try to determine if you really need to use JavaScript on a given page as well. Ask yourself whether you are using it to add functionality to the page or just to make its appearance better. JavaScript can do a lot of neat things to a Web page, but, if it causes your page to break in certain browsers, you should avoid using it. A fine line exists between what you gain in functionality and what you expose as problems, so be sure to test your code with as many browsers and platforms as possible.

Depending on programmers’ objectives when using JavaScript, they might be able to impose browser requirements. If they have stated that their pages only work in browsers later than Netscape 6 and Internet Explorer 5, it is safe for them to use JavaScript 1.3 or lower for their scripting needs. This immediately eliminates them from having to support older browsers, which can save many lines of code. Developers might not be able to impose these restrictions on a Web site, but it is likely that they can on Web-based applications.

Overall, programmers should be smart about using the language. They need to evaluate what their objectives are and who their audience is. When these requirements are defined, they can reverse engineer the project to determine what code they need to write. This is often a much easier approach than starting with an idea and trying to make it work in all circumstances.

Now that you’ve taken a quick look at some of the general issues to analyze before using JavaScript, take a look at what you can do with it. The following sections contain some of the common uses of the language, as as some more complex and specific uses.

Web Page Enhancements

Web page enhancements were the first real use of JavaScript. Any of you who have been working with the Internet since the release of Netscape Navigator 2 probably remember those annoying scrolling messages in the status bar of the browser window. This was one of the first enhancements done using JavaScript. Even though it became annoying, it definitely caught the eye of users.

Another popular item JavaScript is used for is writing the current date and time to a page. Some sites write the date and time the document was last modified, whereas others write the current date and time. This is widely used on sites that are news related in which the date of the document is very important to readers.

A final example of using JavaScript to enhance Web pages is to produce rollover buttons. This usually occurs on pages in which the linked images change when a user rolls over them. It is also possible to program in a down state when a user clicks and holds their mouse button down on the image. Even though this is a simple enhancement, it makes a page look and feel more professional. This effect allows a Web site to give the user the same experience as using his favorite application, be it a Web browser, a word processor, or a money manager.

These three implementations of JavaScript to enhance Web pages are pretty simple, but are by no means the limit of what can be done. Many sites have used JavaScript for advertisements, pop-up navigation windows, page redirects, and validating forms. Because the language is executed within the browser’s environment and is often used to complement HTML publishing, there is virtually no limit to what can be done.

Interactive E-Mail

Interactive e-mail is something that has come about within e-mail applications. It wasn’t long ago that many of these programs were only able to read text e-mails. These programs now have the capability to render HTML e-mail within their interface, which extends the formatting options a user can exploit. This not only improves the look and feel of the e-mail, but it also improves the readability of it. If a user wants something in italic, you can put it in italic.

Because HTML e-mail has become widely used in the Internet community, more and more e-mail applications are supporting it. In addition to HTML, Netscape and Microsoft’s most recent e-mail applications support JavaScript within the body of an e-mail message (assuming that the user has it enabled). This makes it possible for a user to send HTML e-mails containing JavaScript that is interpreted when the recipient reads the message.

As a programmer, you need to keep in mind that an e-mail application is not a browser. Users are very particular about what they experience in their messages, and overuse of JavaScript could lead to annoying your recipients. JavaScript should be used sparingly in e-mails. It should be reserved for simple page enhancements such as image and link rollovers or calling ads within your message. Anything beyond this could cause problems when the application interprets your scripts.

Web-Based Applications

Web-based applications are probably the most useful instances of JavaScript. They allow a programmer to set user browser requirements, which in turn gives them a head start on the version of JavaScript they have at their disposal. This also results in limited exposure to browser bugs because programmers can define which browsers they support.

One of the most common uses of JavaScript within Web-based applications seems to be in controlling forms on a page. This can be anything from checking a user’s values before submission to dynamically adjusting the values based on user-selected data. By implementing JavaScript at this level, a programmer is able to reduce the amount of user error when submitting forms. No more invalid credit card numbers because one digit too many was entered. No more usernames and passwords submitted as e-mail addresses, and no more incomplete forms.

JavaScript is also used in more full-blown Web-based applications. These applications are not necessarily for the common Internet user to experience, but rather are interfaces to enterprise level applications a company might have purchased. Some of the more common applications are used for reporting or ad delivery and management. Because the content on the application’s pages is dynamic and always changing, a developer usually interfaces the application with a database or system process to build the pages on-the-fly. Using JavaScript allows developers to verify items before requests are made, as well as add an appealing look and feel to the application.

Windows Scripting

Microsoft’s Windows Script Host comes with Windows 98, including Windows 2000, and can be installed in Windows 95 and NT 4 systems. This scripting host is language independent for ActiveX scripting on Windows 32-bit systems. Language independent means that a variety of programming languages can be used in conjunction with the host. The reason it’s mentioned in this book is that it natively supports JScript—Microsoft’s implementation of ECMAScript.

Using JScript in the scripting host allows an administrator or user to create scripts that perform various tasks on the operating system. These can be as simple as logon scripts or can be used to call ActiveX controls to perform more complex tasks. If you work in the Microsoft Windows environment, you will find this implementation of JScript can be very helpful.

JavaScript Resources

When you program a lot in a particular language, especially one that’s Internet related, you come across many resources. Additionally, when you program a lot in a particular language, especially one that’s Internet related, you need many resources. So to conclude this introductory chapter, we have included some resources for you. There’s everything from general information to core documentation and references to newsgroups—all on the JavaScript language and all online.

General Information

One of the most important types of resources in any given language is the general resource. Even if a book carries comprehensive coverage of a topic, it might not have conveyed the subject matter in a form that you understood. For this reason, you might want to study the same topic from a different person’s perspective. Table 1.4 lists some resources that will allow you to do this.

Table 1.4 General Resources

Image

Reference

Another important resource for any programmer is true reference documentation. This documentation represents information about that language as defined by standards or by companies who have built or implemented the language. Table 1.5 includes a list of online resources for the various reference documents out there today.

Table 1.5 Reference Resources

Image

Newsgroups

The final resource that we are going to discuss is the old standby—Usenet, or Newsgroups. Newsgroups are often a very good forum to post questions about problems and see responses to issues that others are having. It’s global collaboration at its best and often is an overlooked resource. Table 1.6 lists some of our favorites, so be sure to check them out before giving up on any project.

Table 1.6 Newsgroup Resources

Image

Moving On

This chapter covers the overview of the JavaScript language. As you can see, JavaScript is actually a very powerful scripting language that has many advantages. Security features are in place, and other implementations of the language make it worth any programmer’s time to learn.

In the next chapter, you will take a look at the details of the language. Details that will give you, the programmer, an understanding of how the language deals with operators, data types, variables, functions, loops, conditionals, as well as how to correctly implement JavaScript within the body of an HTML document.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.143.239