Professional JavaScript for Web Developers 3rd Edition

www.it-ebooks.info ffirs.indd ivffirs.indd iv 12/8/11 12:54:54 PM12/8/11 12:54:54 PM www.it-ebooks.info PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS FO...

24 downloads 874 Views 52MB Size

www.it-ebooks.info

www.it-ebooks.info ffirs.indd iv

12/8/11 12:54:54 PM

PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS FOREWORD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii CHAPTER 1

What Is JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

CHAPTER 2

JavaScript in HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13

CHAPTER 3

Language Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

CHAPTER 4

Variables, Scope, and Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

CHAPTER 5

Reference Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

CHAPTER 6

Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

CHAPTER 7

Function Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

CHAPTER 8

The Browser Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

CHAPTER 9

Client Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

CHAPTER 10

The Document Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309

CHAPTER 11

DOM Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

CHAPTER 12

DOM Levels 2 and 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381

CHAPTER 13

Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431

CHAPTER 14

Scripting Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511

CHAPTER 15

Graphics with Canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551

CHAPTER 16

HTML5 Scripting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591

CHAPTER 17

Error Handling and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607

CHAPTER 18

XML in JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641

CHAPTER 19

ECMAScript for XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671

CHAPTER 20

JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691

CHAPTER 21

Ajax and Comet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701

CHAPTER 22

Advanced Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731

CHAPTER 23

Offline Applications and Client-Side Storage . . . . . . . . . . . . . . . . . . . . . 765

CHAPTER 24

Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801 Continues www.it-ebooks.info

ffirs.indd i

12/8/11 12:54:52 PM

CHAPTER 25

Emerging APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835

APPENDIX A

ECMAScript Harmony . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857

APPENDIX B

Strict Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877

APPENDIX C

JavaScript Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885

APPENDIX D

JavaScript Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897

www.it-ebooks.info ffirs.indd ii

12/8/11 12:54:54 PM

PROFESSIONAL

JavaScript® for Web Developers

www.it-ebooks.info ffirs.indd iii

12/8/11 12:54:54 PM

www.it-ebooks.info ffirs.indd iv

12/8/11 12:54:54 PM

PROFESSIONAL

JavaScript® for Web Developers Third Edition

Nicholas C. Zakas

John Wiley & Sons, Inc.

www.it-ebooks.info ffirs.indd v

12/8/11 12:54:54 PM

Professional JavaScript® for Web Developers, Third Edition Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256

www.wiley.com Copyright © 2012 by John Wiley & Sons, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-1-118-02669-4 ISBN: 978-1-118-22219-5 (ebk) ISBN: 978-1-118-23309-2 (ebk) ISBN: 978-1-118-26080-7 (ebk) Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 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. Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com. Library of Congress Control Number: 2011943911 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 affi liates, in the United States and other countries, and may not be used without written permission. JavaScript is a registered trademark of Oracle America, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.

www.it-ebooks.info ffirs.indd vi

12/8/11 12:54:56 PM

To my parents, who never cease to support and inspire me.

www.it-ebooks.info ffirs.indd vii

12/8/11 12:54:56 PM

www.it-ebooks.info ffirs.indd viii

12/8/11 12:54:56 PM

ABOUT THE AUTHOR

NICHOLAS C. ZAKAS has been working with the web for over a decade. During that

time, he has worked both on corporate intranet applications used by some of the largest companies in the world and on large-scale consumer websites such as My Yahoo! and the Yahoo! homepage. As a presentation architect at Yahoo!, Nicholas guided front-end development and standards for some of the most-visited websites in the world. Nicholas is an established speaker and regularly gives talks at companies, conferences, and meetups regarding front-end best practices and new technology. He has authored several books, including Professional Ajax and High Performance JavaScript, and writes regularly on his blog at http://www.nczonline.net/. Nicholas’s Twitter handle is @slicknet.

ABOUT THE TECHNICAL EDITOR

JOHN PELOQUIN is a front-end engineer with over ten years of JavaScript experience ranging across

applications of all sizes. John earned his B.A. in mathematics from the University of California at Berkeley and is currently a lead developer for a health care startup where he makes use of the latest in front-end technologies. Prior to editing this volume, John edited JavaScript 24-Hour Trainer by Jeremy McPeak (Wiley, 2010). When he is not coding or collecting errata, John is often found engaged in mathematics, philosophy, or juggling.

www.it-ebooks.info ffirs.indd ix

12/8/11 12:54:57 PM

www.it-ebooks.info ffirs.indd x

12/8/11 12:54:57 PM

CREDITS

EXECUTIVE EDITOR

PRODUCTION MANAGER

Carol Long

Tim Tate

SENIOR PROJECT EDITOR

VICE PRESIDENT AND EXECUTIVE GROUP PUBLISHER

Kevin Kent

Richard Swadley TECHNICAL EDITOR

John Peloquin

VICE PRESIDENT AND EXECUTIVE PUBLISHER

PRODUCTION EDITOR

Neil Edde

Kathleen Wisor ASSOCIATE PUBLISHER COPY EDITOR

Jim Minatel

Katherine Burt

PROJECT COORDINATOR, COVER

EDITORIAL MANAGER

Katie Crocker

Mary Beth Wakefield FREELANCER EDITORIAL MANAGER

Rosemarie Graham ASSOCIATE DIRECTOR OF MARKETING

David Mayhew

PROOFREADER

Nicole Hirschman INDEXER

Robert Swanson

MARKETING MANAGER

COVER DESIGNER

Ashley Zurcher

LeAndra Young

BUSINESS MANAGER

COVER IMAGE

Amy Knies

© iStock/Andrew Rich

www.it-ebooks.info ffirs.indd xi

12/8/11 12:54:57 PM

www.it-ebooks.info ffirs.indd xii

12/8/11 12:54:58 PM

ACKNOWLEDGMENTS

EVEN THOUGH THE AUTHOR’S NAME is the one that graces the cover of a book, no book is the result

of one person’s efforts, and I’d like to thank a few of the people involved in this one. First and foremost, thanks to John Wiley & Sons for continuing to give me opportunities to write. They were the only people willing to take a risk on an unknown author for the fi rst edition of Professional JavaScript for Web Developers, and for that I will be forever grateful. Thanks to the staff of John Wiley & Sons, specifically Kevin Kent and John Peloquin, who both did an excellent job keeping me honest and dealing with my frequent changes to the book as I was writing. I’d also like to thank everyone who provided feedback on draft chapters of the book: Rob Friesel, Sergey Ilinsky, Dan Kielp, Peter-Paul Koch, Jeremy McPeak, Alex Petrescu, Dmitry Soshnikov, and Juriy “Kangax” Zaytsev. Your feedback made this book something that I’m extremely proud of. A special thanks to Brendan Eich for his corrections to the history of JavaScript included in Chapter 1. Last, but certainly not least, thanks to Rey Bango for writing the foreword of this book. I had the pleasure of meeting Rey for the fi rst time in 2010 after conversing online for several years. He’s one of the truly nice guys in the industry, and I’m honored that he agreed to lend his time to this book.

www.it-ebooks.info ffirs.indd xiii

12/8/11 12:54:58 PM

www.it-ebooks.info ffirs.indd xiv

12/8/11 12:54:58 PM

CONTENTS

FOREWORD

xxxi

INTRODUCTION

xxxiii

CHAPTER 1: WHAT IS JAVASCRIPT?

A Short History JavaScript Implementations

1

2 3

ECMAScript The Document Object Model (DOM) The Browser Object Model (BOM)

JavaScript Versions Summary

3 6 9

10 11

CHAPTER 2: JAVASCRIPT IN HTML

The <script> Element

13

13

Tag Placement Deferred Scripts Asynchronous Scripts Changes in XHTML Deprecated Syntax

16 16 17 18 20

Inline Code versus External Files Document Modes The

Hello World!



❘ 7

html head title Sample Page

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

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.

p Hello World!

Why the DOM Is Necessary

FIGURE 1-2

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 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.

www.it-ebooks.info c01.indd 7

12/8/11 9:23:19 AM

8



CHAPTER 1 WHAT IS JAVASCRIPT?

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) and 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 fi rst 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 didn’t introduce new DOM functionality in versions 6 and 7, though version 8 introduced some bug fi xes. 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 percent standards-compliant browser, and their work paid off.)

www.it-ebooks.info c01.indd 8

12/8/11 9:23:36 AM

JavaScript Implementations

❘ 9

DOM support became a huge priority for most browser vendors, and efforts have been ongoing to improve support with each release. 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–8

Level 1 (almost all)

Internet Explorer 9+

Level 1, Level 2, Level 3

Opera 1–6



Opera 7–8.x

Level 1 (almost all), Level 2 (partial)

Opera 9–9.9

Level 1, Level 2 (almost all), Level 3 (partial)

Opera 10+

Level 1, Level 2, Level 3 (partial)

Safari 1.0.x

Level 1

Safari 2+

Level 1, Level 2 (partial)

Chrome 1+

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 made the BOM truly unique, and often problematic, was that it was the only part of a JavaScript implementation that had no related standard. This changed with the introduction of HTML5, which sought to codify much of the BOM as part of a formal specification. Thanks to HTML5, a lot of the confusion surrounding the BOM has dissipated. 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

www.it-ebooks.info c01.indd 9

12/8/11 9:23:42 AM

10



CHAPTER 1 WHAT IS JAVASCRIPT?



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 existed for the BOM for a long time, 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 defi nes its own properties and methods for these and other objects. With HTML5 now available, the implementation details of the BOM are expected to grow in a much more compatible way. 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.5

1.8.1

Firefox 3.6

1.8.2

www.it-ebooks.info c01.indd 10

12/8/11 9:23:42 AM

Summary

❘ 11

The numbering scheme was based on the idea that Firefox 4 would 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, the evolution of JavaScript happened in such a way that this was no longer possible. There is currently no target implementation for JavaScript 2.0.

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. Furthermore, 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 defi ned 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 3 is generally good across all browsers, and support for ECMAScript 5 is growing, whereas support for the DOM varies widely. The BOM, recently codified in HTML5, can vary from browser to browser, though there are some commonalities that are assumed to be available.

www.it-ebooks.info c01.indd 11

12/8/11 9:23:43 AM

www.it-ebooks.info c01.indd 12

12/8/11 9:23:49 AM

2 JavaScript in HTML WHAT’S IN THIS CHAPTER? ➤

Using the <script> element



Comparing inline and external scripts



Examining how document modes affect JavaScript



Preparing for JavaScript-disabled experiences

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.

THE <SCRIPT> ELEMENT The primary method of inserting JavaScript into an HTML page is via the <script> element. This element was created by Netscape and first implemented in Netscape Navigator 2. It was later added to the formal HTML specification. There are six attributes for the <script> element: ➤

async — Optional. Indicates that the script should begin downloading immediately

but should not prevent other actions on the page such as downloading resources or waiting for other scripts to load. Valid only for external script files. ➤

charset — Optional. The character set of the code specified using the src attribute.

This attribute is rarely used, because most browsers don’t honor its value. ➤

defer — Optional. Indicates that the execution of the script can safely be deferred

until after the document’s content has been completely parsed and displayed. Valid only for external scripts. Internet Explorer 7 and earlier also allow for inline scripts.

www.it-ebooks.info c02.indd 13

12/8/11 9:26:01 AM

14



CHAPTER 2 JAVASCRIPT IN HTML



language — Deprecated. Originally indicated the scripting language being used by the code block (such as “JavaScript”, “JavaScript1.2”, or “VBScript”). Most browsers ignore

this attribute; it should not be used. ➤

src — Optional. Indicates an external fi le that contains code to be executed.



type — Optional. Replaces language; indicates the content type (also called MIME type)

of the scripting language being used by the code block. Traditionally, this value has always been “text/javascript”, though both “text/javascript” and “text/ecmascript” are deprecated. JavaScript fi les are typically served with the “application/x-javascript” MIME type even though setting this in the type attribute may cause the script to be ignored. Other values that work in non–Internet Explorer browsers are “application/ javascript” and “application/ecmascript”. The type attribute is still typically set to “text/javascript” by convention and for maximum browser compatibility. This attribute is safe to omit, as “text/javascript” is assumed when missing. There are two ways to use the <script> element: embed JavaScript code directly into the page or include JavaScript from an external fi le. To include inline JavaScript code, place JavaScript code inside the <script> element directly, as follows: <script type=”text/javascript”> function sayHi(){ alert(“Hi!”); }

The JavaScript code contained inside a <script> element is interpreted from top to bottom. In the case of this example, a function defi nition is interpreted and stored inside the interpreter environment. The rest of the page content is not loaded and/or displayed until after all of the code inside the <script> element has been evaluated. When using inline JavaScript code, keep in mind that you cannot have the string “” anywhere in your code. For example, the following code causes an error when loaded into a browser: <script type=”text/javascript”> function sayScript(){ alert(“”); }

Because of the way that inline scripts are parsed, the browser sees the string “” as if it were the closing tag. This problem can be avoided easily by escaping the “/” character, as in this example: <script type=”text/javascript”> function sayScript(){ alert(“<\/script>”); }

www.it-ebooks.info c02.indd 14

12/8/11 9:26:04 AM

The <script> Element

❘ 15

The changes to this code make it acceptable to browsers and won’t cause any errors. To include JavaScript from an external fi le, the src attribute is required. The value of src is a URL linked to a fi le containing JavaScript code, like this: <script type=”text/javascript” src=”example.js”>

In this example, an external fi le named example.js is loaded into the page. The fi le itself need only contain the JavaScript code that would occur between the opening <script> and closing tags. As with inline JavaScript code, processing of the page is halted while the external fi le is interpreted. (There is also some time taken to download the fi le.) In XHTML documents, you can omit the closing tag, as in this example: <script type=”text/javascript” src=”example.js” />

This syntax should not be used in HTML documents, because it is invalid HTML and won’t be handled properly by some browsers, most notably Internet Explorer.

By convention, external JavaScript files have a .js extension. This is not a requirement, because browsers do not check the file extension of included JavaScript files. This leaves open the possibility of dynamically generating JavaScript code using JSP, PHP, or another server-side scripting language. Keep in mind, though, that servers often use the file extension to determine the correct MIME type to apply to the response. If you don’t use a .js extension, double-check that your server is returning the correct MIME type.

It’s important to note that a <script> element using the src attribute should not include additional JavaScript code between the <script> and tags. If both are provided, the script fi le is downloaded and executed while the inline code is ignored. One of the most powerful and most controversial parts of the <script> element is its ability to include JavaScript fi les from outside domains. Much like an element, the <script> element’s src attribute may be set to a full URL that exists outside the domain on which the HTML page exists, as in this example: <script type=”text/javascript” src=”http://www.somewhere.com/afile.js”>

Code from an external domain will be loaded and interpreted as if it were part of the page that is loading it. This capability allows you to serve up JavaScript from various domains if necessary. Be careful, however, if you are referencing JavaScript fi les located on a server that you don’t control. A malicious programmer could, at any time, replace the file. When including JavaScript fi les from a different domain, make sure you are the domain owner or the domain is owned by a trusted source. Regardless of how the code is included, the <script> elements are interpreted in the order in which they appear in the page so long as the defer and async attributes are not present. The fi rst

www.it-ebooks.info c02.indd 15

12/8/11 9:26:05 AM

16



CHAPTER 2 JAVASCRIPT IN HTML

<script> element’s code must be completely interpreted before the second <script> element begins

interpretation, the second must be completed before the third, and so on.

Tag Placement Traditionally, all <script> elements were placed within the element on a page, such as in this example: Example HTML Page <script type=”text/javascript” src=”example1.js”> <script type=”text/javascript” src=”example2.js”>

The main purpose of this format was to keep external file references, both CSS fi les and JavaScript files, in the same area. However, including all JavaScript fi les in the of a document means that all of the JavaScript code must be downloaded, parsed, and interpreted before the page begins rendering (rendering begins when the browser receives the opening tag). For pages that require a lot of JavaScript code, this can cause a noticeable delay in page rendering, during which time the browser will be completely blank. For this reason, modern web applications typically include all JavaScript references in the element, after the page content, as shown in this example: Example HTML Page <script type=”text/javascript” src=”example1.js”> <script type=”text/javascript” src=”example2.js”>

Using this approach, the page is completely rendered in the browser before the JavaScript code is processed. The resulting user experience is perceived as faster, because the amount of time spent on a blank browser window is reduced.

Deferred Scripts HTML 4.01 defi nes an attribute named defer for the <script> element. The purpose of defer is to indicate that a script won’t be changing the structure of the page as it executes. As such, the script can be run safely after the entire page has been parsed. Setting the defer attribute on a <script>

www.it-ebooks.info c02.indd 16

12/8/11 9:26:16 AM

The <script> Element

❘ 17

element signals to the browser that download should begin immediately but execution should be deferred: Example HTML Page <script type=”text/javascript” defer src=”example1.js”> <script type=”text/javascript” defer src=”example2.js”>

Even though the <script> elements in this example are included in the document , they will not be executed until after the browser has received the closing tag. The HTML5 specification indicates that scripts will be executed in the order in which they appear, so the fi rst deferred script executes before the second deferred script, and both will execute before the DOMContentLoaded event (see Chapter 13 for more information). In reality, though, deferred scripts don’t always execute in order or before the DOMContentLoaded event, so it’s best to include just one when possible. As mentioned previously, the defer attribute is supported only for external script fi les. This was a clarification made in HTML5, so browsers that support the HTML5 implementation will ignore defer when set on an inline script. Internet Explorer 4–7 all exhibit the old behavior, while Internet Explorer 8 and above support the HTML5 behavior. Support for the defer attribute was added beginning with Internet Explorer 4, Firefox 3.5, Safari 5, and Chrome 7. All other browsers simply ignore this attribute and treat the script as it normally would. For this reason, it’s still best to put deferred scripts at the bottom of the page.

For XHTML documents, specify the defer attribute as defer=”defer”.

Asynchronous Scripts HTML5 introduces the async attribute for <script> elements. The async attribute is similar to defer in that it changes the way the script is processed. Also similar to defer, async applies only to external scripts and signals the browser to begin downloading the file immediately. Unlike defer, scripts marked as async are not guaranteed to execute in the order in which they are specified. For example: Example HTML Page <script type=”text/javascript” async src=”example1.js”> <script type=”text/javascript” async src=”example2.js”>

www.it-ebooks.info c02.indd 17

12/8/11 9:26:16 AM

18



CHAPTER 2 JAVASCRIPT IN HTML



In this code, the second script fi le might execute before the fi rst, so it’s important that there are no dependencies between the two. The purpose of specifying an async script is to indicate that the page need not wait for the script to be downloaded and executed before continuing to load, and it also need not wait for another script to load and execute before it can do the same. Because of this, it’s recommended that asynchronous scripts not modify the DOM as they are loading. Asynchronous scripts are guaranteed to execute before the page’s load event and may execute before or after DOMContentLoaded (see Chapter 13 for details). Firefox 3.6, Safari 5, and Chrome 7 support asynchronous scripts.

For XHTML documents, specify the async attribute as async=”async”.

Changes in XHTML Extensible HyperText Markup Language, or XHTML, is a reformulation of HTML as an application of XML. The rules for writing code in XHTML are stricter than those for HTML, which affects the <script> element when using embedded JavaScript code. Although valid in HTML, the following code block is invalid in XHTML: <script type=”text/javascript”> function compare(a, b) { if (a < b) { alert(“A is less than B”); } else if (a > b) { alert(“A is greater than B”); } else { alert(“A is equal to B”); } }

In HTML, the <script> element has special rules governing how its contents should be parsed; in XHTML, these special rules don’t apply. This means that the less-than symbol (<) in the statement a < b is interpreted as the beginning of a tag, which causes a syntax error because a less-than symbol must not be followed by a space. There are two options for fi xing the XHTML syntax error. The fi rst is to replace all occurrences of the less-than symbol (<) with its HTML entity (<). The resulting code looks like this:

www.it-ebooks.info c02.indd 18

12/8/11 9:26:22 AM

The <script> Element

❘ 19

<script type=”text/javascript”> function compare(a, b) { if (a < b) { alert(“A is less than B”); } else if (a > b) { alert(“A is greater than B”); } else { alert(“A is equal to B”); } }

This code will now run in an XHTML page; however, the code is slightly less readable. Fortunately, there is another approach. The second option for turning this code into a valid XHTML version is to wrap the JavaScript code in a CDATA section. In XHTML (and XML), CDATA sections are used to indicate areas of the document that contain free-form text not intended to be parsed. This enables you to use any character, including the less-than symbol, without incurring a syntax error. The format is as follows: <script type=”text/javascript”> b) { alert(“A is greater than B”); } else { alert(“A is equal to B”); } } ]]>

In XHTML-compliant web browsers, this solves the problem. However, many browsers are still not XHTML-compliant and don’t support the CDATA section. To work around this, the CDATA markup must be offset by JavaScript comments: <script type=”text/javascript”> // b) { alert(“A is greater than B”); } else { alert(“A is equal to B”); } } //]]>

This format works in all modern browsers. Though a little bit of a hack, it validates as XHTML and degrades gracefully for pre-XHTML browsers.

www.it-ebooks.info c02.indd 19

12/8/11 9:26:27 AM

20



CHAPTER 2 JAVASCRIPT IN HTML

XHTML mode is triggered when a page specifies its MIME type as “application/ xhtml+xml”. Not all browsers officially support XHTML served in this manner.

Deprecated Syntax When the <script> element was originally introduced, it marked a departure from traditional HTML parsing. Special rules needed to be applied within this element, and that caused problems for browsers that didn’t support JavaScript (the most notable being Mosaic). Nonsupporting browsers would output the contents of the <script> element onto the page, effectively ruining the page’s appearance. Netscape worked with Mosaic to come up with a solution that would hide embedded JavaScript code from browsers that didn’t support it. The fi nal solution was to enclose the script code in an HTML comment, like this: <script>

Using this format, browsers like Mosaic would safely ignore the content inside of the <script> tag, and browsers that supported JavaScript had to look for this pattern to recognize that there was indeed JavaScript content to be parsed. Although this format is still recognized and interpreted correctly by all web browsers, it is no longer necessary and should not be used. In XHTML mode, this also causes the script to be ignored because it is inside a valid XML comment.

INLINE CODE VERSUS EXTERNAL FILES Although it’s possible to embed JavaScript in HTML fi les directly, it’s generally considered a best practice to include as much JavaScript as possible using external fi les. Keeping in mind that there are no hard and fast rules regarding this practice, the arguments for using external fi les are as follows: ➤

Maintainability — JavaScript code that is sprinkled throughout various HTML pages turns code maintenance into a problem. It is much easier to have a directory for all JavaScript files so that developers can edit JavaScript code independent of the markup in which it’s used.



Caching — Browsers cache all externally linked JavaScript fi les according to specific settings, meaning that if two pages are using the same fi le, the fi le is downloaded only once. This ultimately means faster page-load times.



Future-proof — By including JavaScript using external fi les, there’s no need to use the XHTML or comment hacks mentioned previously. The syntax to include external files is the same for both HTML and XHTML.

www.it-ebooks.info c02.indd 20

12/8/11 9:26:27 AM

Document Modes

❘ 21

DOCUMENT MODES Internet Explorer 5.5 introduced the concept of document modes through the use of doctype switching. The fi rst two document modes were quirks mode, which made Internet Explorer behave as if it were version 5 (with several nonstandard features), and standards mode, which made Internet Explorer behave in a more standards-compliant way. Though the primary difference between these two modes is related to the rendering of content with regard to CSS, there are also several side effects related to JavaScript. These side effects are discussed throughout the book. Since Internet Explorer fi rst introduced the concept of document modes, other browsers have followed suit. As this adoption happened, a third mode called almost standards mode arose. That mode has a lot of the features of standards mode but isn’t as strict. The main difference is in the treatment of spacing around images (most noticeable when images are used in tables). Quirks mode is achieved in all browsers by omitting the doctype at the beginning of the document. This is considered poor practice, because quirks mode is very different across all browsers, and no level of true browser consistency can be achieved without hacks. Standards mode is turned on when one of the following doctypes is used:

Almost standards mode is triggered by transitional and frameset doctypes, as follows:

www.it-ebooks.info c02.indd 21

12/8/11 9:26:33 AM

22



CHAPTER 2 JAVASCRIPT IN HTML

Because almost standards mode is so close to standards mode, the distinction is rarely made. People talking about “standards mode” may be talking about either, and detection for the document mode (discussed later in this book) also doesn’t make the distinction. Throughout this book, the term standards mode should be taken to mean any mode other than quirks.

THE