Chapter 1. JavaScript Is More Than You Might Think

Welcome to the introductory chapter. After reading this chapter, you'll be able to

  • Understand the history of JavaScript.

  • Recognize the parts of a JavaScript program.

  • Use the javascript pseudoprotocol.

  • Understand where JavaScript fits within a Web page.

  • Understand what JavaScript can and cannot do.

A Brief History of JavaScript

JavaScript isn't Java. There, with that out of the way, we can move on to bigger, more important things, like how to make cool drop-down menus. In all seriousness, JavaScript is the colloquial name for a specification more formally known as ECMAScript. But the name ECMAScript doesn't exactly roll off the tongue. Go ahead, try saying it aloud: "ECMAScript." See? (More on ECMAScript a little later.)

Where did JavaScript come from? You might not know the rich and storied history of JavaScript—and arguably, you may not really care much about it, either. If that's the case, you might be tempted to jump ahead to the next chapter and go straight into coding JavaScript. This, of course, would be a mistake—you'd miss all of the wonderful text below about JavaScript. And besides, understanding a bit about the history of JavaScript is important to understanding how the language is implemented in various environments today.

JavaScript was originally developed by Brendan Eich at Netscape around 1995–1996. Back then, the language was called LiveScript. This would've been a great name for a new language and the story could've ended here. However, in an unfortunate decision, the folks in marketing had their way and the language was renamed to JavaScript. Confusion soon ensued. You see, the Java language was the hot new thing at the time, and someone decided to try to capitalize on Java's popularity. As a result, JavaScript soon found itself associated with the Java language. Unfortunately, Java, though popular in the sense that it was frequently used, had earned somewhat of a bad reputation because some Web sites used Java for presentation or to add useless enhancements to their Web sites (such as annoying scrolling text). The user experience suffered because Java required a plug-in to load into the Web browser, slowing down the browsing process and generally causing grief for those visitors, not to mention accessibility problems. JavaScript has been inexorably linked to Java and its problems ever since. Only recently has JavaScript begun to shake this association.

JavaScript is not a compiled language, which makes it have the look and feel of a language that lacks power. Power programmers of the Internet in the late 1990s initially dismissed JavaScript but soon came to realize its usefulness and strength to both simulate and create interactivity on the World Wide Web. Up until that point, many Web sites were made of simple Hypertext Markup Language (HTML), with graphics that lacked both visual appeal and the ability to interact with the site's content.

Early JavaScript concentrated on client-side form validation and working with images on Web pages to provide rudimentary, though helpful, interactivity and feedback to the visitor. When a visitor to a Web site would fill in a form, JavaScript could be used to instantly validate the contents of the Web form rather than making a round trip to the server. This was a great way to help applications be a little quicker and more responsive by saving the round-trip time, especially in the days before broadband was pervasive.

Enter Internet Explorer 3

With the release of Microsoft Internet Explorer version 3 in 1996, Microsoft included support for core JavaScript, known in Internet Explorer as JScript, along with support for another scripting language, VBScript. Unfortunately, although these languages were similar, they weren't exactly the same in their implementations. Therefore, methods were developed to detect which browser was being used by the Web site visitor and to respond with JavaScript that would work for that particular browser. This process is known as browser detection, which will be discussed in Chapter 14. Browser detection is still used, though it is now frowned upon for most applications.

And Then Came ECMAScript

In mid-1997 Microsoft and Netscape worked with the European Computer Manufacturers Association (ECMA) to release the first version of ECMAScript. Since this time, all browsers from Netscape and Microsoft have implemented versions of the ECMAScript standard. Other popular browsers, such as Firefox and Opera, have also implemented the ECMAScript standard.

The latest version of ECMAScript, formalized in the standard known as ECMA-262, was released in 1999. The good news is that browsers such as Internet Explorer 4 and Netscape 4.5 supported this standard and that every major browser since then has supported the version of JavaScript formalized in the ECMA-262 standard. The bad news is that each browser applies this standard in slightly different ways. This means that incompatibilities still plague developers who use JavaScript.

A fourth edition of ECMAScript is still a work in progress, soon to be released. See http://www.ecma-international.org/ for more information on the standard.

As a developer who will be incorporating JavaScript into your Web applications, you need to account for the differences between interpretations of JavaScript. Doing so might mean implementing a script in slightly different ways, and it also means that you need to test, test, and test again in various browsers and on various platforms. On today's Internet, there is little tolerance for poorly designed applications that work in only one browser.

Important

It is imperative that you test your Web sites in multiple browsers, even Web applications that you don't think will be used outside Internet Explorer. Even if you're sure that your application will be used only in Internet Explorer or that's all that you officially support, you still should test in other browsers. Not only is this important for security, but it also shows that you're being a thorough developer who understands today's Internet technologies.

So Many Standards…

If you're thinking that standards surrounding JavaScript programming are somewhat loosely defined, you'd be right. Each browser supports JavaScript with slight differences, making your job that much more difficult. Trying to write about all these differences is also more difficult than if the language were a single, specific entity, like a certain version of Microsoft Visual Basic or Perl. But it's not, and so your job (and mine) will be to keep track of these differences and account for them as necessary, trying to find common ground as much as possible.

The DOM

Another evolving standard relevant to the JavaScript programmer is the document object model (DOM) standard developed by the World Wide Web Consortium (W3C). The W3C defines the DOM as "a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of documents." What this means for you is that there is a specification to which Web browsers adhere that you can use to work with a Web page in a dynamic manner. The DOM creates a tree structure for HTML and Extensible Markup Language (XML) documents and enables scripting of those objects. JavaScript interacts heavily with the DOM for many important functions.

Like JavaScript, the DOM has been interpreted differently by different browsers, thus making life for a JavaScript programmer that much more interesting. Internet Explorer 4 and previous versions of Netscape included support for an early DOM, known as Level 0. If you use the Level 0 DOM, you can be reasonably assured that you'll find support in those browsers and everything that came after.

Versions 5 and 5.5 of Internet Explorer included some support for Level 1 DOM, while Internet Explorer version 6 and later includes some support for Level 2 DOM. Other browsers, such as Firefox and Opera, support the W3C standards.

If there's one thing that you should take away while learning about JavaScript standards and the related DOM standards, it's that you need to pay particular attention to the code that you write (no surprise there) and the syntax used to implement that code. If you don't, JavaScript can fail miserably and make your page not render in a given browser. Chapter 10, covers the DOM in much greater detail.

Tip

The W3C has an application that can test your Web browser for its support of the various DOM levels. This application can be found at http://www.w3.org/2003/02/06-dom-support.html.

What's in a JavaScript Program?

A JavaScript program consists of statements formed from tokens, operators, and identifiers placed together in an order that is meaningful to a JavaScript interpreter, which is contained in most Web browsers. This seems like a mouthful, but it's really not all that complicated to anyone who has programmed in just about any other language. A statement might be:

var smallNumber = 4;

In that statement, there is a token or reserved word, var, followed by other tokens, such as an identifier, an operator, and a literal. You'll learn more about each of these in Chapter 2, and throughout the book. The purpose of this statement is to set a variable equal to the integer 4.

Like any programming language, statements get put together in an order that makes a program perform one or more functions. Speaking of functions, JavaScript has its own way to define functions, which you'll read much more about in Chapter 7. JavaScript defines several built-in functions that you can use within your programs.

Using the javascript pseudoprotocol and a function

  1. Open a Web browser such as Internet Explorer or Firefox.

  2. In the Address Bar, type the following code and press Enter:

    javascript:alert("Hello World");
  3. When you press Enter, you'll see a dialog box similar to this one:

image with no caption

Congratulations! You've just programmed your first (albeit not very useful) bit of JavaScript code. With this little bit of code, however, you've now seen two important things that you'll likely use in your JavaScript programming endeavors: the javascript pseudoprotocol identifier in a browser, and, more importantly, the alert function. Each of these items will be examined in later chapters, but for now it's enough that you've already learned something that you'll use in the future!

JavaScript is also event-driven, meaning that it can respond to certain events or "things that happen," such as a mouse click or text change within a form field. Connecting JavaScript to an event is central to many forms or common uses of JavaScript. In Chapter 14, you'll see how to respond to events by using JavaScript.

Placing JavaScript on Your Web Page

If you're new to HTML, all you need to know about it for now is that it delineates elements in a Web page using a pair of matching tags in brackets. The closing tag begins with a slash character (/). Elements can be nested within each other. JavaScript fits within <script> tags inside of the <head> </head> and/or <body> </body> tags of a Web page, as in this example:

<html>
<head>
<title>A Web Page Title</title>
<script type = "text/javascript">
// JavaScript Goes Here
</script>
</head>
<body>
<script type = "text/javascript">
// JavaScript can go here too
</script>
</body>
</html>

JavaScript placed in the <body> tags executes as it is encountered. This is helpful when you need to write to the document by using a JavaScript function, as follows (the function calls are shown in bold type):

<head>
<title>A Web Page Title</title>
<script type = "text/javascript">
// JavaScript Goes Here
</script>
</head>
<body>
<script type = "text/javascript">
document.write("hello");
document.write(" world");
</script>
</body>
</html>

When you're using JavaScript on an Extensible Hypertext Markup Language (XHTML) page, the < and & characters are interpreted as XML, which can cause problems for JavaScript. To get around this use the following syntax in an XHTML page:

<script type="text/javascript">
<![CDATA[
// JavaScript Goes Here
]]>
</script>

Yes, it really is that ugly. However, there's an easy fix for this: use external JavaScript files. You'll see in Chapter 2 exactly how to accomplish this simple task.

Tip

Use the Markup Validator regularly until you're comfortable with coding to standards, and always check for validity before releasing your Web project to the public.

What JavaScript Can Do

JavaScript is largely a complementary language, meaning that it's uncommon for an entire application to be written solely in JavaScript without the aid of other languages like HTML and without presentation in a Web browser. There is support for JavaScript in some Adobe products, but JavaScript is primarily used for Web-related programming.

As you'll see (or likely already know), JavaScript is also the J in the acronym AJAX (Asynchronous JavaScript and XML), the darling of the Web 2.0 phenomenon. Beyond that, though, JavaScript is an everyday language providing the interactivity expected, maybe even demanded, by today's Web visitors.

JavaScript can do many things on the client side of the application. It can add the needed interactivity to a Web site by such actions as creating drop-down menus, transforming the text on a page, adding dynamic elements to a page, and helping with form entry.

The rest of this book is about what JavaScript can do. But first let's look at some of the things JavaScript can't do, and please note that neither list is comprehensive.

What JavaScript Can't Do

Of the things that JavaScript can't do, many are the result of JavaScript's usage being somewhat limited to a Web browser environment. This section examines some of the tasks JavaScript can't do and some that JavaScript shouldn't do.

JavaScript Can't Be Forced on a Client

In practical terms, JavaScript relies on another interface or host program for its functionality. This host program is usually the client's Web browser, also known as a user agent. Because JavaScript is a client-side language, it can do only what the client allows it to do.

Some people are still using older browsers that don't support JavaScript at all. Still others won't be able to support many of JavaScript's fancy features due to accessibility, text readers, and other add-on software assisting the browsing experience. And some people might just choose to disable JavaScript because they can, because of security concerns (whether perceived or real), or because of the poor reputation JavaScript has among some people because of certain annoyances like pop-up ads.

No matter the reason, you need to perform some extra work to ensure that the Web site you're designing will be available to those individuals who don't have JavaScript. I can hear your protests already: "But this feature is really [insert your own superlative here: cool, sweet, essential, nice, splendiferous]." Regardless of how nice that feature may be, chances are you'd benefit from better interoperability and more site visitors. In the Tips for Using JavaScript section later in this chapter, I'll offer some pointers you can follow to ensure that JavaScript is used appropriately within your Web site.

It may be helpful to think of this another way. When you build a Web application that gets served from Internet Information Services (IIS) 6.0, you can be reasonably sure that the application should usually work when served from an IIS 6.0 server anywhere. Likewise, when you build an application for Apache 2, you can be sure that it will work on other Apache 2 installations. The same cannot be said for JavaScript, however. When you write an application that works fine on your desktop, it won't necessarily work on the next person's. You can't control how your application will work once it gets sent to the client.

JavaScript Can't Guarantee Data Security

Because JavaScript is run wholly on the client, the developer must learn to let go. As you might expect, letting go of control over your program has serious implications. Once the program is on the client's computer, the client can do many nasty things to the code itself before sending it back to the server. As with any other Web programming, you should never trust any data coming back from the client. Even if you've used JavaScript functions to validate the contents of forms, you still must validate this input again when it gets to the server. A client with JavaScript disabled might send back garbage data through a Web form. If you believe, innocently enough, that your client-side JavaScript function has already checked the data to ensure that it is valid, you may find that invalid data gets back to the server, causing unforeseen and possibly dangerous consequences.

Important

Remember that JavaScript can be disabled on your visitor's computer. Cute tricks like using JavaScript to disable right-clicks or to prevent visitors from viewing the page source simply cannot be relied upon to be successful and shouldn't be used as security measures.

JavaScript Can't Cross Domains

The JavaScript developer also must be aware of the Same-Origin Policy, which dictates that scripts run from within one domain do not have access to the properties from another Internet domain, nor can they affect the scripts and data from another domain. For example, JavaScript can be used to open a new browser window, but the contents of that window are somewhat restricted to the calling script. If a page from my Web site, braingia.org, contains JavaScript, it can't access any JavaScript executed from a different domain, such as microsoft.com. This is the essence of the Same-Origin Policy: to be shared within sites, JavaScript has to be executed in the same location or originate from it.

The Same-Origin Policy frequently arises with frames and with AJAX's XMLHttpRequest object, where multiple JavaScript requests might be sent to different Web servers. I'll discuss some workarounds in Chapter 18. For now, be aware that JavaScript is limited to doing things in your own browser window.

JavaScript Doesn't Do Servers

When developing server-side code such as Visual Basic .NET or PHP (PHP is a recursive acronym that stands for "PHP: Hypertext Preprocessor"), you can be reasonably certain that the server will implement certain functions, such as talking to a database or giving access to modules necessary for the Web application. JavaScript doesn't have access to server-side variables. For example, JavaScript cannot access databases that are located on the server. JavaScript code is limited to what can be done inside the platform on which the script is running, which is typically the browser.

Another shift in thinking if you're familiar with server-side programming is that you won't know what the client is capable of without testing on many different clients. When you're programming server-side, if the server doesn't implement a given function, you'll know it right away because the server-side script will fail when you test it. Naughty administrators aside, the back-end server code implementation shouldn't change on a whim, making it easier to know what you can and cannot code. The same cannot be said for JavaScript code that is intended to run on clients that are completely out of your control.

Tips for Using JavaScript

Several factors go into good Web design, and, really, who arbitrates what is and is not considered good, anyway? One visitor to a site might call it an ugly hodgepodge of colors and text created as if they were put in a sack and shaken until they simply fell out onto the page; the next might love the design and color scheme.

Since you're reading this book, I'll assume that you're looking for some help with using JavaScript to enhance your Web site. I will also assume that you want to use this programming language to help people use your site and to make your site look, feel, and work better.

Design of a Web site is not and will never be entirely objective. The goal of a Web site might be informational, which would dictate one approach, while the goal of another Web site might be connected to an application and therefore calls for specialized design and functionality. However, many popular and seemingly well designed sites have certain aspects in common. I'll try to break those down here, although I ask you to remember that I haven't created a comprehensive list and that these are simply one person's opinions.

A well-designed Web site emphasizes function over form.

When a user visits a Web site, he or she usually wants to obtain information. The more difficult your site is to navigate, the more likely the user will simply move to another site with better navigation.

Animations and blinking bits come and go, but what remain are sites that have basic information presented in a professional, easily accessible manner. Using the latest cool animation software or Web technology makes me think of the days of the HTML <blink> tag. The <blink> tag, for those who never saw it in action, caused the text within it to disappear and reappear on the screen. Nearly all Web developers seem to hate the <blink> tag and what it does to a Web page. Those same developers would be wise to keep in mind that today's cool bling or sweet effect on a Web page will be tomorrow's <blink>. Successful Web sites stick to the basics and use blinky bits only when the content requires them.

Use elements like a site map, alt tags, and simple navigation, and don't require special software or plug-ins for viewing the site's main content. Too often, I visit a Web site, only to be stopped because I need a plug-in or the latest version of this or that player (which I don't have) to navigate the site.

Although site maps, alt tags, and simple navigation may seem quaint, these are indispensible items for accessibility. Text readers and other such technologies that enable sites to be read aloud or navigated by those with disabilities use these objects and frequently have problems with complex JavaScript.

A well-designed Web site follows standards.

Web standards are there to be followed, so ignore them at your own peril. Using a correct DOCTYPE declaration and well-formed HTML helps to ensure that your site will display correctly to your visitors. Validation using the W3C's Markup Validator tool is highly recommended. If your site is broken, fix it!

A well-designed Web site renders correctly in multiple browsers.

Even when Internet Explorer had 90 percent market share, it was never a good idea for programmers to ignore other browsers. Doing so usually meant that accessibility was also ignored, so people with text readers or other add-ons couldn't use the site. People using operating systems other than Microsoft Windows might also be out of luck visiting those sites.

Though Internet Explorer is still the leader among Web visitors, there's a great chance that at least 2 or 3 of every 10 visitors might be using a different browser. Of course, this variance depends largely on the subject matter. The more technical the audience, the more you'll find you need to accommodate browsers other than Internet Explorer. Therefore, if your site appeals to a technical audience, you might need your site to work in Firefox, Safari, or even Lynx.

Regardless of the Web site's subject matter, you never want to turn away visitors because of their choice of browser. Imagine the shopkeeper who turned away 3 of every 10 potential customers just because of their shoes. That shop wouldn't be in business very long—or at the very least, it wouldn't be as successful.

If you strive to follow Web standards, chances are that you'll already be doing most of what you need to do to support multiple browsers. Avoiding proprietary plug-ins for your Web site helps to ensure that it renders correctly, too.

A well-designed Web site uses appropriate technologies at appropriate times.

Speaking of plug-ins, a well-designed Web site doesn't overuse or misuse technology. On a video site, it's appropriate to play videos. Likewise, on a music site, it's appropriate to play background music. This is not the case on other sites. If you feel as though your site needs to have background music playing, go back to the drawing board and examine why you want a Web site in the first place. I still shudder when I think of an attorney's Web site that I once visited. The site started playing the firm's jingle in the background, without my intervention. Friends don't let friends use background music on their site, unless your friend is from the band Rush and you are working on the band's Web site.

Where JavaScript Fits

Today's Web is still evolving. One of the more popular movements over the past year is known as unobtrusive scripting. The unobtrusive scripting paradigm is part of the larger movement called behavioral separation. Behavioral separation calls for structure to be separated from style, both of which are separated from behavior. In this model, HTML or XHTML provides the structure while CSS provides the style and JavaScript provides the behavior. The JavaScript is unobtrusive; it doesn't get in the way. If JavaScript isn't available in the browser, the Web site still works because there's still some other way for the visitor to use the Web site.

When applied properly, unobtrusive script means that any use of JavaScript will fail in a graceful manner. Not assuming that JavaScript will be available, the unobtrusive scripter either makes sure that the page will function without JavaScript or uses proper methods to ensure that JavaScript is available if it's actually required for the site. One such method will be covered in Chapter 14. Unobtrusive scripting is important because it helps to ensure accessibility for those with alternative browsers, text readers, or whatever the case may be.

I'm a proponent of unobtrusive scripting because it tends to mean that standards will be followed and the resulting site will follow the four recommendations I shared in the previous section. Granted, this isn't necessarily the case. One could separate the HTML, CSS, and JavaScript and still end up using proprietary tags, but the tendency when programming in an unobtrusive manner is to pay closer attention to detail and therefore care much more about the end result being standards-compliant.

Throughout this book, I'm going to strive to show you not only the basics of JavaScript but the best way to use JavaScript effectively and, as much as possible, unobtrusively.

Which Browsers Should the Site Support?

Backwards compatibility has been an issue for the Web developer for a long time. Choosing which browser versions to support becomes a tradeoff between the latest functionality available in the newest browsers and the compatible functionality required for older browsers to view the Web site. There is no hard and fast rule for which browsers you should support on your Web site, so the answer is: it depends.

Your decision depends on what you'd like to do with your site and whether you value visits by people using older hardware and software more than you value the added functionality available in later browser versions. Some browsers are just too old to support because they can't render CSS correctly, much less JavaScript. A key to supporting multiple browser versions is to test within them. Obtaining an MSDN account from Microsoft will give you access to legacy products, including older versions of Internet Explorer, so that you can see how your site reacts to a visit from Internet Explorer 4.

Many Web designs and JavaScript functions don't require newer versions of Web browsers. However, as I've already said, it's always a good idea to verify that your site renders correctly in various browsers. Even if extensive testing isn't possible, making the site fail in a graceful manner is also important so that it renders appropriately regardless of the browser being used.

Exercises

  1. True or False: JavaScript is defined by a standards body and is supported on all Web browsers.

  2. True or False: When a visitor whose machine has JavaScript disabled comes to your Web site, then you should block her or his access to the site since there's no valid reason to have JavaScript disabled.

  3. Create a JavaScript definition block that would typically appear on an HTML page within the <head> block.

  4. True or False: It's important to declare the version of JavaScript being used within the DOCTYPE definition block.

  5. True or False: JavaScript can appear in both the <head> block and within the <body> text of an HTML page.

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

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