Professional JavaScript® for Web Developers, 2nd Edition

Published by

Wiley Publishing, Inc.

10475 Crosspoint Boulevard

Indianapolis, IN 46256

www.wiley.com

Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-0-470-22780-0

Library of Congress Cataloging-in-Publication Data

Zakas, Nicholas C.

Professional JavaScript for web developers/Nicholas C. Zakas. — 2nd ed.

p. cm.

Includes index.

ISBN 978-0-470-22780-0 (paper/website)

1. Web site development. 2. JavaScript (Computer program language) I. Title.

TK5105.8885.J38Z34 2008

005.2'762 — dc22

2008045552

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. JavaScript is a registered trademark of Sun Microsystems, Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

Dedicated to my family: mom, dad, Greg, Yiayia, and Papou. We may be few in numbers, but we are mighty! Your constant love and support have made the past couple of years possible.

About the Author

Nicholas C. Zakas has a B.S. in Computer Science from Merrimack College and an M.B.A. from Endicott College. He is the coauthor of Professional Ajax, Second Edition (Wiley, 2007) as well as dozens of online articles. Nicholas works for Yahoo! as a principal front-end engineer on Yahoo!’s front page and a contributor to the Yahoo! User Interface (YUI) Library. He has worked in web development for more than eight years, during which time he has helped develop web solutions in use at some of the largest companies in the world.

Nicholas can be reached through his web site www.nczonline.net.

Credits

Acquisitions Director

Jim Minatel

Senior Development Editor

Kevin Kent

Technical Editor

Alexei Gorkov

Development Editor

Gus Miklos

Production Editor

Rebecca Coleman

Copy Editors

Foxxe Editorial Services, Candace English

Editorial Manager

Mary Beth Wakefield

Production Manager

Tim Tate

Vice President and Executive Group Publisher

Richard Swadley

Vice President and Executive Publisher

Joseph B. Wikert

Project Coordinator, Cover

Lynsey Stanford

Proofreader

Kathryn Duggan

Indexer

Jack Lewis

Acknowledgments

It takes many people to create a single book, and I’d like to thank some people here for their contributions to this work.

First and foremost, thanks to everyone at Wiley for their support: Jim Minatel for once again putting his faith in me; Kevin Kent for dealing with the hectic outline rearrangements I tend to make throughout writing; and Alexei Gorkov, the best technical editor in the world, who makes sure that everything I say is 100-percent accurate.

A big thanks to everyone who provided feedback on draft chapters: David Serduke, Julian Turner, Pete Frueh, Chris Klaiber, Stoyan Stefanov, Ross Harmes, and David Golightly. Your early feedback was really helpful in making this book what it is today.

Last, thanks to Eric Miraglia for his contribution of a foreword. Eric is the reason I ended up at Yahoo!, and it has been a pleasure to work with him for the past two years.

Foreword

JavaScript, for much of its existence, has been the subject of fear, invective, disdain, and misunderstanding. In its early years, many “serious programmers” thought that JavaScript wasn’t serious enough.

By contrast, many liberal arts majors drafted into web-developer service during the dotcom boom thought JavaScript was mysterious and arcane. Many who had both the tenacity and the patience to fully grok JavaScript as a language were nevertheless frustrated by its inconsistent implementation across competing browsers. All of these factors helped lead to a proliferation of awkward and poorly conceived scripts. And, through the extraordinary openness of front-end code on the Web, a lot of bad habits were copied from one site and pasted into the source of another. Thus JavaScript’s bad reputation as a language, which was generally ill-deserved, became intertwined with a deservedly bad reputation surrounding its implementations.

Around 2001 (with the release of Internet Explorer 6), improved browser implementations and improving practice in web development began to converge. The XMLHttpRequest object at the heart of Ajax was slowly being discovered, and a new paradigm of desktop-style user interaction was emerging within the browser. The DOM APIs that allowed JavaScript to manipulate the structure and content of web documents had solidified. CSS, for all the contortions, omissions, and the willful insanity of its implementations by browser vendors, had progressed far enough that beauty and responsiveness could be combined with the Web’s new interactive power. As a result, JavaScript became the subject of a new set of emotions: surprise, delight, and awe. If you think back to the first time you used Google Maps in 2004, you may recall the feeling.

Google Maps was among an emerging class of applications that took browser-based programming as seriously as back-end programming and made us think differently about the application canvas provided by the web browser. (Oddpost, which provided Outlook-style email functionality in a webmail client as early as 2003, was another notable pioneer.) The proliferation of these applications and the increasing market penetration of browsers that supported them led to a genuine renaissance in web application engineering. “Web 2.0” was born, and Ajax became the “it” technology. The Web was suddenly interesting all over again. JavaScript, as the only programming language of the Web, became more interesting, too.

Interesting, but hard to do well. JavaScript and its companion APIs in the Document Object Model (DOM) and Browser Object Model (BOM) were inconsistently implemented, making cross-browser implementations vastly more difficult than they needed to be. The profession of front-end engineering was still young. University curricula had not (and still have not) stepped in to meet the training challenge.

JavaScript, arguably the most important programming language in the world by the end of 2004, was not a first-class subject in the academic sense of the word. A new day was dawning on the Web, and there was a serious question as to whether there would be enough knowledgeable, well-informed engineers to meet the new challenges.

Many technical writers stepped in to fill the gap with books on JavaScript. There were dozens of these over the years, but by and large they were a disappointing lot. Some of them promoted techniques that were relevant only in retrograde browsers; some promoted techniques that were easy to cut and paste but hard to extend and maintain. Puzzlingly, many books on JavaScript seemed to be written by people who didn’t really like JavaScript, who didn’t think you should like it, and who weren’t optimistic about your ability to understand it fully.

One of the genuinely good books in the world of front-end engineering arrived when Nicholas C. Zakas published the first edition of Professional JavaScript for Web Developers in 2005. At the time, my colleagues and I were working at Yahoo! to create the Yahoo! User Interface Library (YUI) as a foundation for front-end engineering here and to evangelize best practices in our nascent discipline. Every Friday, we’d gather in a classroom to talk about the front-end engineering and to teach classes on JavaScript, CSS, and the creation of web applications in the browser. We carefully reviewed the offerings at the time for books that would help new engineers learn how to build robust, standards-based, easy-to-maintain web applications using advanced JavaScript and DOM scripting. As soon as it was published, Zakas’s book became our textbook for JavaScript.

We’ve been using it ever since. We thought so highly of the book that we talked Zakas into coming to Yahoo! to help shape the front-end engineering community here.

What Zakas accomplished with Professional JavaScript for Web Developers is singular: He treated JavaScript as a subject that is both serious and accessible. If you are a programmer, you will learn where JavaScript fits into the broader spectrum of languages and paradigms with which you’re familiar. You’ll learn how its system of inheritance and its intrinsic dynamism are, yes, unconventional but also liberating and powerful. You’ll learn to appreciate JavaScript as a language from a fellow programmer who respects it and understands it.

If you’re one of those liberal arts majors who was drawn into this profession in the boom years and never left, and if you want to fill in the gaps of your understanding of JavaScript, you’ll find Zakas to be the mentor you’ve always wanted — the one who will help you make the transition from “making things work” to “making things that work well.” He’ll leave you with a serious understanding of a serious subject. Best of all, you’ll find that he doesn’t pander to preconceived notions about how deeply you should understand the language. He takes it seriously, and in a patient, accessible way he helps you to do the same.

This second edition of Professional JavaScript for Web Developers — expanded, updated, improved — drops some subjects that are less relevant to the profession today and upgrades the rest with what we’ve learned between 2005 and 2008. These years have been important ones, and Zakas is on the front line of the process of learning. He’s spent those years architecting the current generation of the Web’s most popular personal portal (My Yahoo!) and the next version of the web’s most visited site (Yahoo!’s front page). Insights forged in these complex, ultra-high-volume applications inform every page of this new volume, all passed through Zakas’s unique filter as a teacher/author.

As a result, his solutions go beyond being book-smart and include the kind of practical wisdom you can only get by living and breathing code on a daily basis.

And that’s seriously good news for the rest of us. Professional JavaScript for Web Developers is now even better, even more relevant, and even more important to have on your shelf.

Eric Miraglia, Ph.D.

Sr. Engineering Manager, Yahoo! User Interface Library (YUI)

Sunnyvale, California

Introduction

Some claim that JavaScript is now the most popular programming language in the world, running any number of complex web applications that the world relies on to do business, make purchases, manage processes, and more.

JavaScript is very loosely based on Java, an object-oriented programming language popularized for use on the Web by way of embedded applets. Although JavaScript has a similar syntax and programming methodology, it is not a “light” version of Java. Instead, JavaScript is its own dynamic language, finding its home in web browsers around the world and enabling enhanced user interaction on web sites and web applications alike.

In this book, JavaScript is covered from its very beginning in the earliest Netscape browsers to the present-day incarnations flush with support for the DOM and Ajax. You learn how to extend the language to suit specific needs and how to create seamless client-server communication without intermediaries such as Java or hidden frames. In short, you learn how to apply JavaScript solutions to business problems faced by web developers everywhere.

What Does This Book Cover?

Professional JavaScript for Web Developers, 2nd Edition, provides a developer-level introduction along with the more advanced and useful features of JavaScript.

Starting at the beginning, the book explores how JavaScript originated and evolved into what it is today. A detailed discussion of the components that make up a JavaScript implementation follows, with specific focus on standards such as ECMAScript and the Document Object Model (DOM). The differences in JavaScript implementations used in different popular web browsers are also discussed.

Building on that base, the book moves on to cover basic concepts of JavaScript, including its version of object-oriented programming, inheritance, and its use in various markup languages such as HTML. An in-depth examination of events and event handling is followed by an exploration of browser-detection techniques and a guide to using regular expressions in JavaScript. The book then takes all this knowledge and applies it to creating dynamic user interfaces.

The last part of the book is focused on advanced topics, including performance and memory optimization, best practices, and a look at where JavaScript is going in the future.

Who Is This Book For?

This book is aimed at the following three groups of readers:

Experienced developers familiar with object-oriented programming who are looking to learn JavaScript as it relates to traditional object-oriented (OO) languages such as Java and C++

Web application developers attempting to enhance the usability of their web sites and web applications

Novice JavaScript developers aiming to better understand the language

In addition, familiarity with the following related technologies is a strong indicator that this book is for you:

Java

PHP

ASP.NET

HTML

CSS

XML

This book is not aimed at beginners who lack a basic computer-science background or those looking to add some simple user interactions to web sites. These readers should instead refer to Wrox’s Beginning JavaScript, 3rd Edition (Wiley, 2007).

What You Need to Use This Book

To run the samples in the book, you need the following:

Windows 2000, Windows Server 2003, Windows XP, Vista, or Mac OS X

Internet Explorer 6 or higher, Firefox 2 or higher, Opera 9 or higher, Chrome 0.2 or higher, or Safari 2 or higher.

The complete source code for the samples is available for download at www.wrox.com/.

How This Book Is Structured

This book comprises the following chapters:

Chapter 1, What Is JavaScript? — Explains the origins of JavaScript: where it came from, how it evolved, and what it is today. Concepts introduced include the relationship between JavaScript and ECMAScript, the Document Object Model (DOM), and the Browser Object Model (BOM). A discussion of the relevant standards from the European Computer Manufacturer’s Association (ECMA) and the World Wide Web Consortium (W3C) is also included.

Chapter 2, JavaScript in HTML — Examines how JavaScript is used in conjunction with HTML to create dynamic web pages. This chapter introduces the various ways of embedding JavaScript into a page, including a discussion surrounding the JavaScript content-type and its relationship to the <script> element.

Chapter 3, Language Basics — Introduces basic language concepts, including syntax and flow control statements. This chapter explains the syntactic similarities of JavaScript and other C-based languages and points out the differences. Type coercion is introduced as it relates to built-in operators.

Chapter 4, Variables, Scope, and Memory — Explores how variables are handled in JavaScript given their loosely typed nature. A discussion about the differences between primitive and reference values is included, as is information about execution context as it relates to variables. Also, a discussion about garbage collection in JavaScript explains how memory is reclaimed when variables go out of scope.

Chapter 5, Reference Types — Covers all of the details regarding JavaScript’s built-in reference types, such as Object and Array. Each reference type described in ECMA-262 is discussed both in theory and how it relates to browser implementations.

Chapter 6, Object-Oriented Programming — Explains how to use object-oriented (OO) programming in JavaScript. Since JavaScript has no concept of classes, several popular techniques are explored for object creation and inheritance. Also covered in this chapter is the concept of function prototypes and how that relates to an overall OO approach.

Chapter 7, Anonymous Functions — Explores one of the most powerful aspects of JavaScript: anonymous functions. Topics include closures, how the this object works, the module pattern, and creating private object members.

Chapter 8, The Browser Object Model — Introduces the Browser Object Model (BOM), which is responsible for objects allowing interaction with the browser itself. Each of the BOM objects is covered, including window, document, location, navigator, and screen.

Chapter 9, Client Detection — Explains various approaches to detecting the client machine and its capabilities. Different techniques include capability detection and user-agent string detection. This chapter discusses the pros and cons as well as the situational appropriateness of each approach.

Chapter 10, The Document Object Model — Introduces the Document Object Model (DOM) objects available in JavaScript as defined in DOM Level 1. A brief introduction to XML and its relationship to the DOM gives way to an in-depth exploration of the entire DOM and how it allows developers to manipulate a page.

Chapter 11, DOM Levels 2 and 3 — Builds on the previous chapter, explaining how DOM Levels 2 and 3 augmented the DOM with additional properties, methods, and objects. Compatibility issues between Internet Explorer and other browsers are discussed.

Chapter 12, Events — Explains the nature of events in JavaScript, where they originated, legacy support, and how the DOM redefined how events should work. A variety of devices are covered, including the Wii and iPhone.

Chapter 13, Scripting Forms — Looks at using JavaScript to enhance form interactions and work around browser limitations. The discussions in this chapter focus on individual form elements such as text boxes and select boxes and on data validation and manipulation.

Chapter 14, Error Handling and Debugging — Discusses how browsers handle errors in JavaScript code and presents several ways to handle errors. Debugging tools and techniques are also discussed for each browser, including recommendations for simplifying the debugging process.

Chapter 15, XML in JavaScript — Presents the features of JavaScript used to read and manipulate eXtensible Markup Language (XML) data. This chapter explains the differences in support and objects in various web browsers, and offers suggestions for easier cross-browser coding. This chapter also covers the use of eXtensible Stylesheet Language Transformations (XSLT) to transform XML data on the client.

Chapter 16, ECMAScript for XML — Discusses the ECMAScript for XML (E4X) extension to JavaScript, which is designed to simplify working with XML. This chapter explains the advantages of E4X over using the DOM for XML manipulation.

Chapter 17, Ajax and JSON — Looks at common Ajax techniques, including the use of the XMLHttpRequest object and Internet Explorer’s XDomainRequest object for cross-domain Ajax. This chapter explains the differences in browser implementations and support as well as recommendations for usage.

Chapter 18, Advanced Techniques — Dives into some of the more complex JavaScript patterns, including function currying, partial function application, and dynamic functions. This chapter also covers creating a custom event framework to enable simple event support for custom objects.

Chapter 19, Client-Side Storage — Discusses the various techniques for storing data on the client machine. This chapter begins with a discussion of the most commonly supported feature, cookies, and then discusses newer functionality such as DOM storage.

Chapter 20, Best Practices — Explores approaches to working with JavaScript in an enterprise environment. Techniques for better maintainability are discussed, including coding techniques, formatting, and general programming practices. Execution performance is discussed and several techniques for speed optimization are introduced. Last, deployment issues are discussed, including how to create a build process.

Chapter 21, Upcoming APIs — Introduces APIs being created to augment JavaScript in the browser. Even though these APIs aren’t yet complete or fully implemented, they are on the horizon and browsers have already begun partially implementing their features. This chapter includes discussions on the Selectors API and HTML 5.

Chapter 22, The Evolution of JavaScript — Looks into the future of JavaScript to see where the language is headed. ECMAScript 3.1, ECMAScript 4, and ECMAScript Harmony are discussed.

Conventions

To help you get the most from the text and keep track of what’s happening, a number of conventions are used throughout this book.

Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

Notes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

As for styles in the text:

New terms and important words are italicized when they’re introduced.

Keyboard combinations are shown like this: Ctrl+A.

File names, URLs, and code within the text look like this: persistence.properties.

Code is presented in two different ways:

Monofont type with no highlighting is used for most code examples.

Gray highlighting is used to emphasize code that’s particularly important in the present context.

Source Code

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

Because many books have similar titles, you may find it easiest to search by ISBN. This book’s ISBN is 978-0-470-22780-0.

After you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

Errata

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration and help us provide even higher-quality information.

To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

p2p.wrox.com

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system for you to post messages relating to Wrox books and related technologies, as well as to interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com, you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

1. Go to p2p.wrox.com and click the Register link.

2. Read the terms of use and click Agree.

3. Complete the required information to join as well as any optional information you wish to provide, and click Submit.

4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

You can read messages in the forums without joining P2P, but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

Chapter 1

What Is JavaScript?

When JavaScript first appeared in 1995, its main purpose was to handle some of the input validation that had previously been left to server-side languages such as Perl. Prior to that time, a round-trip to the server was needed to determine if a required field had been left blank or an entered value was invalid. Netscape Navigator sought to change that with the introduction of JavaScript. The capability to handle some basic validation on the client was an exciting new feature at a time when use of telephone modems was widespread. The associated slow speeds turned every trip to the server into an exercise in patience.

Since that time, JavaScript has grown into an important feature of every major web browser on the market. No longer bound to simple data validation, JavaScript now interacts with nearly all aspects of the browser window and its contents. JavaScript is recognized as a full programming language, capable of complex calculations and interactions, including closures, anonymous (lambda) functions, and even metaprogramming. JavaScript has become such an important part of the Web that even alternative browsers, including those on mobile phones and those designed for users with disabilities, support it. Even Microsoft, with its own client-side scripting language called VBScript, ended up including its own JavaScript implementation in Internet Explorer from its earliest version.

The rise of JavaScript from a simple input validator to a powerful programming language could not have been predicted. JavaScript is at once a very simple and very complicated language that takes minutes to learn but years to master. To begin down the path to using JavaScript’s full potential, it is important to understand its nature, history, and limitations.

A Short History

Around 1992, a company called Nombas (later bought by Openwave) began developing an embedded scripting language called C-minus-minus (Cmm for short). The idea behind Cmm was simple: a scripting language powerful enough to replace macros, but still similar enough to C (and C++) that developers could learn it quickly. This scripting language was packaged in a shareware product called CEnvi, which first exposed the power of such languages to developers. Nombas eventually changed the name Cmm to ScriptEase. ScriptEase became the driving force behind Nombas products. When the popularity of Netscape Navigator started peaking, Nombas developed a version of CEnvi that could be embedded into web pages. These early experiments were called Espresso Pages, and they represented the first client-side scripting language used on the World Wide Web. Little did Nombas know that its ideas would become an important foundation for the Internet.

As the Web gained popularity, a gradual demand for client-side scripting languages developed. At the time, most Internet users were connecting over a 28.8 kbps modem even though web pages were growing in size and complexity. Adding to users’ pain was the large number of round-trips to the server required for simple form validation. Imagine filling out a form, clicking the Submit button, waiting 30 seconds for processing, and then being met with a message indicating that you forgot to complete a required field. Netscape, at that time on the cutting edge of technological innovation, began seriously considering the development of a client-side scripting language to handle simple processing.

Brendan Eich, who worked for Netscape at the time, began developing a scripting language called LiveScript for the release of Netscape Navigator 2 in 1995, with the intention of using it both in the browser and on the server (where it was to be called LiveWire). Netscape entered into a development alliance with Sun Microsystems to complete the implementation of LiveScript in time for release. Just before Netscape Navigator 2 was officially released, Netscape changed LiveScript’s name to JavaScript to capitalize on the buzz that Java was receiving from the press.

Because JavaScript 1.0 was such a hit, Netscape released version 1.1 in Netscape Navigator 3. The popularity of the fledgling Web was reaching new heights and Netscape had positioned itself to be the leading company in the market. At this time, Microsoft decided to put more resources into a competing browser named Internet Explorer. Shortly after Netscape Navigator 3 was released, Microsoft introduced Internet Explorer 3 with a JavaScript implementation called JScript (so called to avoid any possible licensing issues with Netscape). This major step for Microsoft into the realm of web browsers in August 1996 is now a date that lives in infamy for Netscape, but it also represented a major step forward in the development of JavaScript as a language.

Microsoft’s implementation of JavaScript meant that there were three different JavaScript versions floating around: JavaScript in Netscape Navigator, JScript in Internet Explorer, and CEnvi in ScriptEase. Unlike C and many other programming languages, JavaScript had no standards governing its syntax or features, and the three different versions only highlighted this problem. With industry fears mounting, it was decided that the language must be standardized.

In 1997, JavaScript 1.1 was submitted to the European Computer Manufacturers Association (Ecma) as a proposal. Technical Committee #39 (TC39) was assigned to “standardize the syntax and semantics of a general purpose, cross-platform, vendor-neutral scripting language” (http://www.ecma-international.org/memento/TC39.htm). Made up of programmers from Netscape, Sun, Microsoft, Borland, and other companies with interest in the future of scripting, TC39 met for months to hammer out ECMA-262, a standard defining a new scripting language named ECMAScript.

The following year, the International Organization for Standardization and International Electrotechnical Commission (ISO/IEC) also adopted ECMAScript as a standard (ISO/IEC-16262). Since that time, browsers have tried, with varying degrees of success, to use ECMAScript as a basis for their JavaScript implementations.

JavaScript Implementations

Though JavaScript and ECMAScript are often used synonymously, JavaScript is much more than just what is defined in ECMA-262. Indeed, a complete JavaScript implementation is made up of the following three distinct parts (see Figure 1-1):

The Core (ECMAScript)

The Document Object Model (DOM)

The Browser Object Model (BOM)

Figure 1-1

ECMAScript

ECMAScript, the language defined in ECMA-262, isn’t tied to web browsers. In fact, the language has no methods for input or output whatsoever. ECMA-262 defines this language as a base upon which more-robust scripting languages may be built. Web browsers are just one host environment in which an ECMAScript implementation may exist. A host environment provides the base implementation of ECMAScript as well as extensions to the language designed to interface with the environment itself. Extensions, such as the Document Object Model (DOM), use ECMAScript’s core types and syntax to provide additional functionality that’s more specific to the environment. Other host environments include ScriptEase and Adobe Flash.

What exactly does ECMA-262 specify if it doesn’t reference web browsers? On a very basic level, it describes the following parts of the language:

Syntax

Types

Statements

Keywords

Reserved words

Operators

Objects

ECMAScript is simply a description of a language implementing all of the facets described in the specification. JavaScript implements ECMAScript, but so does Adobe ActionScript and OpenView ScriptEase (see Figure 1-2).

Figure 1-2

ECMAScript Editions

The different versions of ECMAScript are defined as editions (referring to the edition of ECMA-262 in which that particular implementation is described). The most recent edition of ECMA-262 is edition 4, released in 2007. The first edition of ECMA-262 was essentially the same as Netscape’s JavaScript 1.1, but with all references to browser-specific code removed and a few minor changes: ECMA-262 required support for the Unicode standard (to support multiple languages) and that objects be platform-independent (Netscape JavaScript 1.1 actually had different implementations of objects, such as the Date object, depending on the platform). This was a major reason why JavaScript 1.1 and 1.2 did not conform to the first edition of ECMA-262.

The second edition of ECMA-262 was largely editorial. The standard was updated to get into strict agreement with ISO/IEC-16262 and didn’t feature any additions, changes, or omissions. ECMAScript implementations typically don’t use the second edition as a measure of conformance.

The third edition of ECMA-262 was the first real update to the standard. It provided updates to string handling, the definition of errors, and numeric outputs. It also added support for regular expressions, new control statements, try-catch exception handling, and small changes to better prepare the standard for internationalization. To many, this marked the arrival of ECMAScript as a true programming language.

The fourth edition of ECMA-262 was a complete overhaul of the language. In response to the popularity of JavaScript on the Web, developers began revising ECMAScript to meet the growing demands of web development around the world. In response, ECMA TC39 reconvened to decide the future of the language. The resulting specification defined an almost completely new language based on the third edition. The fourth edition includes strongly typed variables, new statements and data structures, true classes and classical inheritance, as well as new ways to interact with data (this is discussed in Chapter 22).

As an alternate proposal, a specification called “ECMAScript 3.1” was developed as a smaller evolution of the language by a subgroup of TC39, who believed that the fourth edition was too big of a jump for the language. The result was a smaller proposal with incremental changes to the languages (discussed in Chapter 22).

What Does ECMAScript Conformance Mean?

ECMA-262 lays out the definition of ECMAScript conformance. To be considered an implementation of ECMAScript, an implementation must do the following:

Support all “types, values, objects, properties, functions, and program syntax and semantics” (ECMA-262, p. 1) as they are described in ECMA-262.

Support the Unicode character standard.

Additionally, a conforming implementation may do the following:

Add “additional types, values, objects, properties, and functions” that are not specified in ECMA-262. ECMA-262 describes these additions as primarily new objects or new properties of objects not given in the specification.

Support “program and regular expression syntax” that is not defined in ECMA-262 (meaning that the built-in regular-expression support is allowed to be altered and extended).

These criteria give implementation developers a great amount of power and flexibility for developing new languages based on ECMAScript, which partly accounts for its popularity.

ECMAScript Support in Web Browsers

Netscape Navigator 3 shipped with JavaScript 1.1 in 1996. That same JavaScript 1.1 specification was then submitted to Ecma as a proposal for the new standard, ECMA-262. With JavaScript’s explosive popularity, Netscape was very happy to start developing version 1.2. There was, however, one problem: Ecma hadn’t yet accepted Netscape’s proposal.

A little after Netscape Navigator 3 was released, Microsoft introduced Internet Explorer 3. This version of IE shipped with JScript 1.0, which was supposed to be equivalent to JavaScript 1.1. However, because of undocumented and improperly replicated features, JScript 1.0 fell far short of JavaScript 1.1.

Netscape Navigator 4 was shipped in 1997 with JavaScript 1.2 before the first edition of ECMA-262 was accepted and standardized later that year. As a result, JavaScript 1.2 is not compliant with the first edition of ECMAScript even though ECMAScript was supposed to be based on JavaScript 1.1.

The next update to JScript occurred in Internet Explorer 4 with JScript version 3.0 (version 2.0 was released in Microsoft Internet Information Server version 3.0 but was never included in a browser). Microsoft put out a press release touting JScript 3.0 as the first truly ECMA-compliant scripting language in the world. At that time, ECMA-262 hadn’t yet been finalized, so JScript 3.0 suffered the same fate as JavaScript 1.2: it did not comply with the final ECMAScript standard.

Netscape opted to update its JavaScript implementation in Netscape Navigator 4.06 to JavaScript 1.3, which brought Netscape into full compliance with the first edition of ECMA-262. Netscape added support for the Unicode standard and made all objects platform-independent while keeping the features that were introduced in JavaScript 1.2.

When Netscape released its source code to the public as the Mozilla project, it was anticipated that JavaScript 1.4 would be shipped with Netscape Navigator 5. However, a radical decision to completely redesign the Netscape code from the bottom up derailed that effort. JavaScript 1.4 was released only as a server-side language for Netscape Enterprise Server and never made it into a web browser.

As of 2008, the five major web browsers (Internet Explorer, Firefox, Safari, Chrome, and Opera) all comply with the third edition of ECMA-262. Only one, Firefox, has made an attempt to comply with the fourth edition of the standard. Internet Explorer 8 was the first to start implementing the unfinished ECMAScript 3.1 specification. The following table lists ECMAScript support in the most popular web browsers:

Browser | ECMAScript Compliance
Netscape Navigator 2 | —
Netscape Navigator 3 | —
Netscape Navigator 4–4.05 | —
Netscape Navigator 4.06–4.79 | Edition 1
Netscape 6+ (Mozilla 0.6.0+) | Edition 3
Internet Explorer 3 | —
Internet Explorer 4 | —
Internet Explorer 5 | Edition 1
Internet Explorer 5.5-7 | Edition 3
Internet Explorer 8 | Edition 3.1*
Opera 6–7.1 | Edition 2
Opera 7.2+ | Edition 3
Safari 1-2.0.x | Edition 3*
Safari 3+ | Edition 3
Chrome 0.2+ | Edition 3
Firefox 1–2 | Edition 3
Firefox 3 | Edition 4*
Firefox 3.1 | Edition 4*
Firefox 4.0** | Edition 4

*Incomplete implementations

**Planned

The Document Object Model (DOM)

The Document Object Model (DOM) is an application programming interface (API) for XML that was extended for use in HTML. The DOM maps out an entire page as a hierarchy of nodes. Each part of an HTML or XML page is a type of a node containing different kinds of data. Consider the following HTML page:

<html>
    <head>
        <title>Sample Page</title>
    </head>
    <body>
        <p>Hello World!</p>
    </body>
</html>

This code can be diagrammed into a hierarchy of nodes using the DOM (see Figure 1-3).

Figure 1-3

By creating a tree to represent a document, the DOM allows developers an unprecedented level of control over its content and structure. Nodes can be removed, added, replaced, and modified easily by using the DOM API.

Why the DOM Is Necessary

With Internet Explorer 4 and Netscape Navigator 4 each supporting different forms of Dynamic HTML (DHTML), developers for the first time could alter the appearance and content of a web page without reloading it. This represented a tremendous step forward in web technology, but also a huge problem. Netscape and Microsoft went separate ways in developing DHTML, thus ending the period when developers could write a single HTML page that could be accessed by any web browser.

It was decided that something had to be done to preserve the cross-platform nature of the Web. The fear was that if someone didn’t rein in Netscape and Microsoft, the Web would develop into two distinct factions that were exclusive to targeted browsers. It was then that the World Wide Web Consortium (W3C), the body charged with creating standards for web communication, began working on the DOM.

DOM Levels

DOM Level 1 became a W3C recommendation in October of 1998. It consisted of two modules: the DOM Core, which provided a way to map the structure of an XML-based document to allow for easy access to and manipulation of any part of a document, and the DOM HTML, which extended the DOM Core by adding HTML-specific objects and methods.

Note that the DOM is not JavaScript-specific, and indeed has been implemented in numerous other languages. For web browsers, however, the DOM has been implemented using ECMAScript and now makes up a large part of the JavaScript language.

Whereas the goal of DOM Level 1 was to map out the structure of a document, the aims of DOM Level 2 were much broader. This extension of the original DOM added support for mouse and user-interface events (long supported by DHTML), ranges, traversals (methods to iterate over a DOM document), and support for Cascading Style Sheets (CSS) through object interfaces. The original DOM Core introduced in Level 1 was also extended to include support for XML namespaces.

DOM Level 2 introduced the following new modules of the DOM to deal with new types of interfaces:

DOM Views — Describes interfaces to keep track of the various views of a document (the document before and after CSS styling, for example)

DOM Events — Describes interfaces for events and event handling

DOM Style — Describes interfaces to deal with CSS-based styling of elements

DOM Traversal and Range — Describes interfaces to traverse and manipulate a document tree

DOM Level 3 further extends the DOM with the introduction of methods to load and save documents in a uniform way (contained in a new module called DOM Load and Save) as well as methods to validate a document (DOM Validation). In Level 3, the DOM Core is extended to support all of XML 1.0, including XML Infoset, XPath, and XML Base.

When reading about the DOM, you may come across references to DOM Level 0. Note that there is no standard called DOM Level 0; it is simply a reference point in the history of the DOM. DOM Level 0 is considered to be the original DHTML supported in Internet Explorer 4.0 and Netscape Navigator 4.0.

Other DOMs

Aside from the DOM Core and DOM HTML interfaces, several other languages have had their own DOM standards published. The languages in the following list are XML-based, and each DOM adds methods and interfaces unique to a particular language:

Scalable Vector Graphics (SVG) 1.0

Mathematical Markup Language (MathML) 1.0

Synchronized Multimedia Integration Language (SMIL)

Additionally, other languages have developed their own DOM implementations, such as Mozilla’s XML User Interface Language (XUL). However, only the languages in the preceding list are standard recommendations from W3C.

DOM Support in Web Browsers

The DOM had been a standard for some time before web browsers started implementing it. Internet Explorer made its first attempt with version 5, but it didn’t have any realistic DOM support until version 5.5, when it implemented most of DOM Level 1. Internet Explorer hasn’t introduced new DOM functionality in versions 6 and 7, though version 8 introduces some bug fixes.

For Netscape, no DOM support existed until Netscape 6 (Mozilla 0.6.0) was introduced. After Netscape 7, Mozilla switched its development efforts to the Firefox browser. Firefox 3 supports all of Level 1, nearly all of Level 2, and some parts of Level 3. (The goal of the Mozilla development team was to build a 100% standards-compliant browser, and their work paid off.)

DOM support became a huge priority for most browser vendors, and efforts have been ongoing to improve support with each release. Internet Explorer now lags far behind the other three major browsers in DOM support, being stuck at a partial implementation of DOM Level 1. Chrome 0.2+, Opera 9, and Safari 3 support all of DOM Level 1 and most of DOM Level 2. The following table shows DOM support for popular browsers:

Browser | DOM Compliance
Netscape Navigator 1.–4.x | —
Netscape 6+ (Mozilla 0.6.0+) | Level 1, Level 2 (almost all), Level 3 (partial)
Internet Explorer 2–4.x | —
Internet Explorer 5 | Level 1 (minimal)
Internet Explorer 5.5-7 | Level 1 (almost all)
Opera 1–6 | —
Opera 7–8.x | Level 1 (almost all), Level 2 (partial)
Opera 9+ | Level 1, Level 2 (almost all), Level 3 (partial)
Safari 1.0.x | Level 1
Safari 2+ | Level 1, Level 2 (partial)
Chrome 0.2+ | Level 1, Level 2 (partial)
Firefox 1+ | Level 1, Level 2 (almost all), Level 3 (partial)

The Browser Object Model (BOM)

The Internet Explorer 3 and Netscape Navigator 3 browsers featured a Browser Object Model (BOM) that allowed access and manipulation of the browser window. Using the BOM, developers can interact with the browser outside of the context of its displayed page. What makes the BOM truly unique, and often problematic, is that it is the only part of a JavaScript implementation that has no related standard.

Primarily, the BOM deals with the browser window and frames, but generally any browser-specific extension to JavaScript is considered to be a part of the BOM. The following are some such extensions:

The capability to pop up new browser windows

The capability to move, resize, and close browser windows

The navigator object, which provides detailed information about the browser

The location object, which gives detailed information about the page loaded in the browser

The screen object, which gives detailed information about the user’s screen resolution

Support for cookies

Custom objects such as XMLHttpRequest and Internet Explorer’s ActiveXObject

Because no standards exist for the BOM, each browser has its own implementation. There are some de facto standards, such as having a window object and a navigator object, but each browser defines its own properties and methods for these and other objects. A detailed discussion of the BOM is included in Chapter 8.

JavaScript Versions

Mozilla, as a descendant from the original Netscape, is the only browser vendor that has continued the original JavaScript version-numbering sequence. When the Netscape source code was spun off into an open-source project (named the Mozilla Project), the last browser version of JavaScript was 1.3. (As mentioned previously, version 1.4 was implemented on the server exclusively.) As the Mozilla Foundation continued work on JavaScript, adding new features, keywords, and syntaxes, the JavaScript version number was incremented. The following table shows the JavaScript version progression in Netscape/Mozilla browsers:

Browser | JavaScript Version
Netscape Navigator 2 | 1.0
Netscape Navigator 3 | 1.1
Netscape Navigator 4 | 1.2
Netscape Navigator 4.06 | 1.3
Netscape 6+ (Mozilla 0.6.0+) | 1.5
Firefox 1 | 1.5
Firefox 1.5 | 1.6
Firefox 2 | 1.7
Firefox 3 | 1.8
Firefox 3.1 | 1.9
Firefox 4 | 2.0

The numbering scheme is based on the idea that Firefox 4 will feature JavaScript 2.0, and each increment in the version number prior to that point indicates how close the JavaScript implementation is to the 2.0 proposal. Though this was the original plan, it is unclear if Mozilla will continue along this path given the popularity of the ECMAScript 3.1 proposal.

It’s important to note that only the Netscape/Mozilla browsers follow this versioning scheme. Internet Explorer, for example, has different version numbers for JScript. These JScript versions don’t correspond whatsoever to the JavaScript versions mentioned in the preceding table. Further, most browsers talk about JavaScript support in relation to their level of ECMAScript compliance and DOM support.

Summary

JavaScript is a scripting language designed to interact with web pages and is made up of the following three distinct parts:

ECMAScript, which is defined in ECMA-262 and provides the core functionality

The Document Object Model (DOM), which provides methods and interfaces for working with the content of a web page

The Browser Object Model (BOM), which provides methods and interfaces for interacting with the browser

There are varying levels of support for the three parts of JavaScript across the five major web browsers (Internet Explorer, Firefox, Chrome, Safari, and Opera). Support for ECMAScript edition 3 is generally good across all browsers, whereas support for the DOM varies widely. The BOM, the only part of JavaScript that has no corresponding standard, can vary from browser to browser though there are some commonalities that are assumed to be available.

Chapter 2

JavaScript in HTML

The introduction of JavaScript into web pages immediately ran into the Web’s predominant language, HTML. As part of its original work on JavaScript, Netscape tried to figure out how to make JavaScript coexist in HTML pages without breaking those pages’ rendering in other browsers. Through trial, error, and controversy, several decisions were finally made and agreed upon to bring universal scripting support to the Web. Much of the work done in these early days of the Web has survived and become formalized in the HTML specification.

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!