JavaScript has come a long way from its humble beginnings in 1995 as part of the Netscape browser, to the high-performance JIT interpreters of today. Even just five years ago developers were blown away by Ajax and the yellow fade technique; now, complex JavaScript apps run into the hundreds of thousands of lines.
In the last year, a new breed of JavaScript applications has appeared, giving an experience people were used to on the desktop, but that was unheard of on the Web. Gone are the slow page requests every time a user interacts with an application; instead, JavaScript engines are now so powerful we can keep state client side, giving a much more responsive and improved experience.
Itâs not just JavaScript engines that have improved; CSS3 and HTML5 specs havenât finished the drafting stage, but they are already widely supported by modern browsers such as Safari, Chrome, Firefox, andâto some extentâIE9. Beautiful interfaces can be coded in a fraction of the time previously required, and without all that notorious image cutting and splicing. Support for HTML5 and CSS3 is getting better every day, but youâll need to decideâbased on your client baseâwhether to use these technologies.
Moving state to the client side is no simple task. It requires a completely different development approach to server-side applications. You need to think about structure, templating, communicating with the server, frameworks, and much more. Thatâs where this book comes in; Iâll take you through all the steps necessary to create state-of-the-art JavaScript applications.
This book isnât for JavaScript newbies, so if youâre unfamiliar with the basics of the language, I advise you to pick up one of the many good books on the subject, such as JavaScript: The Good Parts by Douglas Crockford (OâReilly). This book is aimed at developers with some JavaScript experience, perhaps using a library like jQuery, who want to get into building more advanced JavaScript applications. Additionally, many sections of the bookâespecially the appendixesâwill also be a useful reference for experienced JavaScript developers.
- Chapter 1
The chapter starts with a discussion of JavaScriptâs history and covers some of the underlying influences of its current implementation and community. We then give you an introduction to the MVC architectural pattern, in addition to exploring JavaScriptâs constructor functions, prototypal inheritance, and how to create your own class library.
- Chapter 2
This chapter gives you a brief primer on browser events, including their history, API, and behavior. Weâll cover how to bind to events with jQuery, use delegation, and create custom events. Weâll also explore using non-DOM events with the PubSub pattern.
- Chapter 3
This chapter explains how to use MVC models in your application, as well as for loading and manipulating remote data. Weâll explain why MVC and namespacing are important and then build our own ORM library to manage model data. Next, weâll cover how to load in remote data using JSONP and cross-domain Ajax. Finally, youâll learn how to persist model data using HTML5 Local Storage and submitting it to a RESTful server.
- Chapter 4
This chapter demonstrates how to use a controller pattern to persist state on the client side. Weâll discuss how to use modules to encapsulate logic and prevent global namespace pollution, then weâll cover how to cleanly interface controllers with views, listening to events and manipulating the DOM. Finally, weâll discuss routing, first using the URLâs hash fragment, and then using the newer HTML5 History API, making sure to explain the pros and cons of both approaches.
- Chapter 5
This is where we cover views and JavaScript templating. We cover the different ways of dynamically rendering views, as well as various templating libraries and where to actually store the templates (inline in the page, in script tags, or with remote loading). Then, youâll learn about data bindingâconnecting your model controllers and views to dynamically synchronize model data and view data.
- Chapter 6
In this chapter, weâll get into the details of JavaScript dependency management using CommonJS modules. Youâll learn the history and thinking behind the CommonJS movement, how to create CommonJS modules in the browser, and various module loader libraries to help you with this, such as Yabble and RequireJS. Next, weâll discuss how to automatically wrap up modules server side, increasing performance and saving time. Finally, weâll cover various alternatives to CommonJS, such as Sprockets and LABjs.
- Chapter 7
Here, weâll get into some of the benefits HTML5 gives us: the File API. Weâll cover browser support, multiple uploads, receiving files that are dragged onto the browser, and files from clipboard events. Next, weâll explore reading files using blobs and slices, and displaying the result in the browser. Weâll cover uploading files in the background using the new XMLHttpRequest Level 2 specification, and finally, weâll show you how to give your users live upload progress bars and how to integrate uploads with jQueryâs Ajax API.
- Chapter 8
Weâll take a look at some of the exciting developments with real-time applications and WebSockets. First, the chapter covers real timeâs rather turbulent history and its current support in the browsers. Then, weâll get into the details of WebSockets and their high-level implementation, browser support, and JavaScript API. Next, weâll demonstrate a simple RPC server that uses WebSockets to connect up servers and clients. Weâll then take a look at Socket.IO and learn how real time fits into applicationsâ architecture and user experience.
- Chapter 9
This chapter covers testing and debugging, a crucial part of JavaScript web application development. Weâll look at the issues surrounding cross-browser testing, which browsers you should test in, and unit tests and testing libraries, such as QUnit and Jasmine. Next, weâll take a look at automated testing and continuous integration servers, such as Selenium. Weâll then get into the debugging side of things, exploring Firefox and WebKitâs Web Inspectors, the console, and using the JavaScript debugger.
- Chapter 10
This chapter covers another importantâbut often neglectedâpart of JavaScript web applications: deployment. Chiefly, weâll consider performance and how to use caching, minification, gzip compression, and other techniques to decrease your applicationâs initial load time. Finally, weâll briefly cover how to use CDNs to serve static content on your behalf, and how to use the browserâs built-in auditor, which can be immensely helpful in improving your siteâs performance.
- Chapter 11
The next three chapters give you an introduction to some popular JavaScript libraries for application development. Spine is a lightweight MVC-compliant library that uses many of the concepts covered in the book. Weâll take you through the core parts of the library: classes, events, models, and controllers. Finally, weâll build an example contacts manager application that will demonstrate what weâve learned from the chapter.
- Chapter 12
Backbone is an extremely popular library for building JavaScript applications, and this chapter will give you a thorough introduction. Weâll take you through the core concepts and classes of Backbone, such as models, collections, controllers, and views. Next, weâll explore syncing model data with the server using RESTful JSON queries and how to respond to Backbone appropriately server side. Finally, weâll build an example to-do list application that will demonstrate much of the library.
- Chapter 13
This chapter explores the JavaScriptMVC library, a popular jQuery-based framework for building JavaScript web applications. Youâll learn all the basics of JavaScriptMVC, such as classes, models, and controllers, as well as using client-side templates to render views. The chapter ends with a practical CRUD list example, demonstrating how easy it is to create abstract, reusable, memory-safe widgets with JavaScriptMVC.
- Appendix A
This appendix provides a brief introduction to jQuery, which is useful if you feel you need to brush up on the library. Most of the bookâs examples use jQuery, so itâs important to be familiar with it. Weâll cover most of the core API, such as traversing the DOM, manipulating the DOM, and event binding, triggering, and delegating. Next, weâll approach jQueryâs Ajax API, making GET and POST JSON requests. Weâll then cover jQuery extensions and how to use encapsulation to ensure youâre being a good web citizen. Finally, weâll take a look at a practical example: creating a Growl jQuery plug-in.
- Appendix B
Appendix B covers Less, a superset of CSS that extends its syntax with variables, mixins, operations, and nested rules. Less can really reduce the amount of CSS you need to writeâespecially when it comes to CSS3 vendorâspecific rules. This appendix covers Lessâs major syntax enhancements and how to use the command lineâs tools and JavaScript library to compile Less files down to CSS.
- Appendix C
The last appendix is a CSS3 reference. It provides a bit of background on CSS3, explains vendor prefixes, and then takes you through the major additions to the specification. Among other CSS3 features, this appendix covers rounded corners,
rgba
colors, drop shadows, gradients, transitions, and transformations. It ends with a discussion about graceful degradation using Modernizr and a practical example of using the new box-sizing specification.
The following typographical conventions are used in this book:
- Italic
Indicates new terms, URLs, email addresses, filenames, file extensions, and events.
Constant width
Indicates computer code in a broad sense, including commands, arrays, elements, statements, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, event handlers, XML tags, HTML tags, macros, the contents of files, and the output from commands.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values determined by context.
Note
This icon signifies a tip, suggestion, or general note.
Warning
This icon indicates a warning or caution.
This bookâs accompanying files are hosted on GitHub. You can view them online or download a zip locally. All the assets are separated by chapter, and any required libraries are also included. Most examples in this book are also available as standalone files.
Whenever a particular asset is referenced inside a chapter, it will be in the form of assets/chapter_number/name.
Throughout this book weâll use the assert()
and assertEqual()
functions to demonstrate the value
of variables or the result of a function call. assert()
is just shorthand for indicating that a
particular variable resolves to true; it is a common pattern thatâs
especially prevalent in automated testing. assert()
takes two arguments: a value and an
optional message. If the value doesnât equal true, the function will throw
an error:
var assert = function(value, msg) { if ( !value ) throw(msg || (value + " does not equal true")); };
assertEqual()
is shorthand for
indicating that one variable equals another. It works similarly to
assert()
, but it accepts two values. If
the two values arenât equal, the assertion fails:
var assertEqual = function(val1, val2, msg) { if (val1 !== val2) throw(msg || (val1 + " does not equal " + val2)); };
Using the two functions is very straightforward, as you can see in the example below. If the assertion fails, youâll see an error message in the browserâs console:
assert( true ); // Equivalent to assertEqual() assert( false === false ); assertEqual( 1, 1 );
Iâve slightly sugar-coated assertEqual()
since, as it stands, object
comparison will fail unless the objects share the same reference in
memory. The solution is a deep comparison, and weâve included an example
of this in assets/ch00/deep_equality.html.
A lot of the examples in this book rely on jQuery, an extremely popular JavaScript library that simplifies events, DOM traversing, manipulation, and Ajax. Iâve decided this for various reasons, but itâs mostly because jQuery greatly clarifies examples, and it is closer to the JavaScript most people write in the real world.
If you havenât used jQuery, I strongly advise you to check it out. It has an excellent API that provides a good abstraction over the DOM. A brief jQuery primer is included in Appendix A.
Built as a companion to this book, Holla is a JS group chat application. Holla is a good example application because it encompasses various best practices covered in this book. Among other things, Holla will show you how to:
Use CSS3 and HTML5 to create beautiful interfaces
Drag and drop to upload files
Lay out your code using Sprockets and Less
Use WebSockets to push data to clients
Create a stateful JavaScript application
Clone the code from Hollaâs GitHub repository and take a look. Many of the examples in this book have been taken from Hollaâs source; see Figure 1.
I wrote this book as I traveled around the world for a year. I wrote some parts in African huts without electricity and Internet, others in Japanese washitsus overlooking temples and blossoming trees, and some even on remote Cambodian islands. In short, I had a great time writing this, and I hope reading it gives you just as much pleasure.
Some people deserve their share of the blame. Thanks go to Stuart Eccles, Tim Malbon, Ben Griffins, and Sean OâHalpin for giving me the chances and opportunity to find my passion; and to James Adam, Paul Battley, and Jonah Fox for mentoring and putting up with my asininities.
Thanks also to the technical reviewers, who really helped shape the book: Henrik Joreteg, Justin Meyer, Lea Verou, Addy Osmani, Alex Barbara, Max Williams, and Julio Cesar Ody.
Most importantly, thanks to my parents for their unwavering support.
Note
Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly.
With a subscription, you can read any page and watch any video from our library online. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features.
OâReilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from OâReilly and other publishers, sign up for free at http://my.safaribooksonline.com.
Please address comments and questions concerning this book to the publisher:
OâReilly Media, Inc. |
1005 Gravenstein Highway North |
Sebastopol, CA 95472 |
(800) 998-9938 (in the United States or Canada) |
(707) 829-0515 (international or local) |
(707) 829-0104 (fax) |
We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:
http://www.oreilly.com/catalog/9781449303518 |
To comment or ask technical questions about this book, send email to:
bookquestions@oreilly.com |
For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Get JavaScript Web Applications now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.