O'Reilly logo

JavaScript Web Applications by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Preface

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.

Who Is This Book For?

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.

How This Book Is Organized

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 EmberJS library, a popular MVC framework for building JavaScript web applications. Ember is a bit more full-featured than Spine and Backbone, and provides more structure and conventions.

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.

Conventions Used in This Book

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.

Accompanying Files

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.

Code Conventions

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.

jQuery Examples

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.

Holla

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.

Holla, an example chat application
Figure 1. Holla, an example chat application

Author’s Note

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.

Safari® Books Online

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.

How to Contact Us

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:

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required