- •Contents at a Glance
- •Contents
- •Foreword
- •About the Authors
- •About the Technical Reviewer
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •An Overview of This Book
- •Example Code and Companion Web Site
- •Contacting the Authors
- •Overview of HTML5
- •The Story So Far—The History of HTML5
- •The Myth of 2022 and Why It Doesn’t Matter
- •Who Is Developing HTML5?
- •A New Vision
- •Compatibility and Paving the Cow Paths
- •Utility and the Priority of Constituencies
- •Interoperability Simplification
- •Universal Access
- •A Plugin–Free Paradigm
- •What’s In and What’s Out?
- •What’s New in HTML5?
- •New DOCTYPE and Character Set
- •New and Deprecated Elements
- •Semantic Markup
- •Simplifying Selection Using the Selectors API
- •JavaScript Logging and Debugging
- •window.JSON
- •DOM Level 3
- •Monkeys, Squirrelfish, and Other Speedy Oddities
- •Summary
- •Using the Canvas API
- •Overview of HTML5 Canvas
- •History
- •What Is a Canvas?
- •Canvas Coordinates
- •When Not to Use Canvas
- •Fallback Content
- •CSS and Canvas
- •Browser Support for HTML5 Canvas
- •Using the HTML5 Canvas APIs
- •Checking for Browser Support
- •Adding a Canvas to a Page
- •Applying Transformations to Drawings
- •Working with Paths
- •Working with Stroke Styles
- •Working with Fill Styles
- •Filling Rectangular Content
- •Drawing Curves
- •Inserting Images into a Canvas
- •Using Gradients
- •Using Background Patterns
- •Scaling Canvas Objects
- •Using Canvas Transforms
- •Using Canvas Text
- •Applying Shadows
- •Working with Pixel Data
- •Implementing Canvas Security
- •Building an Application with HTML5 Canvas
- •Practical Extra: Full Page Glass Pane
- •Practical Extra: Timing Your Canvas Animation
- •Summary
- •Working with Scalable Vector Graphics
- •Overview of SVG
- •History
- •Understanding SVG
- •Scalable Graphics
- •Creating 2D Graphics with SVG
- •Adding SVG to a Page
- •Simple Shapes
- •Transforming SVG Elements
- •Reusing Content
- •Patterns and Gradients
- •SVG Paths
- •Using SVG Text
- •Putting the Scene Together
- •Building an Interactive Application with SVG
- •Adding Trees
- •Adding the updateTrees Function
- •Adding the removeTree Function
- •Adding the CSS Styles
- •The Final Code
- •Summary
- •Working with Audio and Video
- •Overview of Audio and Video
- •Video Containers
- •Audio and Video Codecs
- •Audio and Video Restrictions
- •Browser Support for Audio and Video
- •Using the Audio and Video API
- •Checking for Browser Support
- •Accessibility
- •Understanding Media Elements
- •Working with Audio
- •Working with Video
- •Practical Extras
- •Summary
- •Using the Geolocation API
- •About Location Information
- •Latitude and Longitude Coordinates
- •Where Does Location Information Come From?
- •IP Address Geolocation Data
- •GPS Geolocation Data
- •Wi-Fi Geolocation Data
- •Cell Phone Geolocation Data
- •User–Defined Geolocation Data
- •Browser Support for Geolocation
- •Privacy
- •Triggering the Privacy Protection Mechanism
- •Dealing with Location Information
- •Using the Geolocation API
- •Checking for Browser Support
- •Position Requests
- •Building an Application with Geolocation
- •Writing the HTML Display
- •Processing the Geolocation Data
- •The Final Code
- •Practical Extras
- •What’s My Status?
- •Show Me on a Google Map
- •Summary
- •Using the Communication APIs
- •Cross Document Messaging
- •Understanding Origin Security
- •Browser Support for Cross Document Messaging
- •Using the postMessage API
- •Building an Application Using the postMessage API
- •XMLHttpRequest Level 2
- •Cross-Origin XMLHttpRequest
- •Progress Events
- •Browser Support for HTML5 XMLHttpRequest Level 2
- •Using the XMLHttpRequest API
- •Building an Application Using XMLHttpRequest
- •Practical Extras
- •Structured Data
- •Framebusting
- •Summary
- •Using the WebSocket API
- •Overview of WebSocket
- •Real-Time and HTTP
- •Understanding WebSocket
- •Writing a Simple Echo WebSocket Server
- •Using the WebSocket API
- •Checking for Browser Support
- •Basic API Usage
- •Building a WebSocket Application
- •Coding the HTML File
- •Adding the WebSocket Code
- •Adding the Geolocation Code
- •Putting It All Together
- •The Final Code
- •Summary
- •Using the Forms API
- •Overview of HTML5 Forms
- •HTML Forms Versus XForms
- •Functional Forms
- •Browser Support for HTML5 Forms
- •An Input Catalog
- •Using the HTML5 Forms APIs
- •New Form Attributes and Functions
- •Checking Forms with Validation
- •Validation Feedback
- •Building an Application with HTML5 Forms
- •Practical Extras
- •Summary
- •Working with Drag-and-Drop
- •Web Drag-and-Drop: The Story So Far
- •Overview of HTML5 Drag-and-Drop
- •The Big Picture
- •Events to Remember
- •Drag Participation
- •Transfer and Control
- •Building an Application with Drag-and-Drop
- •Getting Into the dropzone
- •Handling Drag-and-Drop for Files
- •Practical Extras
- •Customizing the Drag Display
- •Summary
- •Using the Web Workers API
- •Browser Support for Web Workers
- •Using the Web Workers API
- •Checking for Browser Support
- •Creating Web Workers
- •Loading and Executing Additional JavaScript
- •Communicating with Web Workers
- •Coding the Main Page
- •Handling Errors
- •Stopping Web Workers
- •Using Web Workers within Web Workers
- •Using Timers
- •Example Code
- •Building an Application with Web Workers
- •Coding the blur.js Helper Script
- •Coding the blur.html Application Page
- •Coding the blurWorker.js Web Worker Script
- •Communicating with the Web Workers
- •The Application in Action
- •Example Code
- •Summary
- •Using the Storage APIs
- •Overview of Web Storage
- •Browser Support for Web Storage
- •Using the Web Storage API
- •Checking for Browser Support
- •Setting and Retrieving Values
- •Plugging Data Leaks
- •Local Versus Session Storage
- •Other Web Storage API Attributes and Functions
- •Communicating Web Storage Updates
- •Exploring Web Storage
- •Building an Application with Web Storage
- •The Future of Browser Database Storage
- •The Web SQL Database
- •The Indexed Database API
- •Practical Extras
- •JSON Object Storage
- •A Window into Sharing
- •Summary
- •Overview of HTML5 Offline Web Applications
- •Browser Support for HTML5 Offline Web Applications
- •Using the HTML5 Application Cache API
- •Checking for Browser Support
- •Creating a Simple Offline Application
- •Going Offline
- •Manifest Files
- •The ApplicationCache API
- •Application Cache in Action
- •Building an Application with HTML5 Offline Web Applications
- •Creating a Manifest File for the Application Resources
- •Creating the HTML Structure and CSS for the UI
- •Creating the Offline JavaScript
- •Check for ApplicationCache Support
- •Adding the Update Button Handler
- •Add Geolocation Tracking Code
- •Adding Storage Code
- •Adding Offline Event Handling
- •Summary
- •The Future of HTML5
- •Browser Support for HTML5
- •HTML Evolves
- •WebGL
- •Devices
- •Audio Data API
- •Touchscreen Device Events
- •Peer-to-Peer Networking
- •Ultimate Direction
- •Summary
- •Index
CHAPTER 12 ■ CREATING OFFLINE WEB APPLICATIONS
Similarly, the internal page chrome://appcache-internals/ provides details about the contents of the different application caches stored on your system. It also provides a way to view the contents and remove these caches entirely as shown in Figure 12-2.
Figure 12-2. Viewing application cache entries in Chrome
Browser Support for HTML5 Offline Web Applications
For a complete overview of the current browser support, including mobile support, refer to http://caniuse.com and search for Offline Web Applications or Application Cache. If you have to support older browsers, it’s always a good idea to first see whether Application Cache is supported before you use the API. The section “Checking for Browser Support” later in this chapter will show you how you can programmatically check for browser support.
Using the HTML5 Application Cache API
In this section, we will explore the specifics of how you can use the Offline Web Applications API.
Checking for Browser Support
Before you try to use the Offline Web Applications API, it is a good idea to check for browser support. Listing 12-1 shows how you can do that.
Listing 12-1. Checking Browser Support for the Offline Web Applications API
if(window.applicationCache) {
// this browser supports offline applications
}
297
CHAPTER 12 ■ CREATING OFFLINE WEB APPLICATIONS
Creating a Simple Offline Application
Let’s say that you want to create a one-page application that consists of an HTML document, a style sheet, and a JavaScript file. To add offline support to your HTML5 application, you include a manifest attribute on the html element as shown in the Listing 12-2.
Listing 12-2. The manifest Attribute on the HTML Element
<!DOCTYPE html>
<html manifest="application.appcache">
.
.
.
</html>
Alongside the HTML document, provide a manifest file with the *.appcache extension) specifying which resources to cache. Listing 12-3 shows the contents of an example cache manifest file.
Listing 12-3. Contents of an Example Cache Manifest File
CACHE MANIFEST example.html example.js example.css example.gif
Going Offline
To make applications aware of intermittent connectivity, there are additional events exposed by HTML5 browsers. Your applications may have different modes for online and offline behavior. Some additions to the window.navigator object make that easier. First, navigator.onLine is a Boolean property that indicates whether the browser believes it is online. Of course, a true value of onLine is not a definite assurance that the servers that your web application must communicate with are reachable from the user’s machine. On the other hand, a false value means the browser will not even attempt to connect out over the network. Listing 12-4 shows how you can check to see if your page is online or offline.
Listing 12-4. Checking Online Status
// When the page loads, set the status to online or offline function loadDemo() {
if (navigator.onLine) { log("Online");
} else { log("Offline");
}
}
// Now add event listeners to notify a change in online status window.addEventListener("online", function(e) {
log("Online"); }, true);
298
CHAPTER 12 ■ CREATING OFFLINE WEB APPLICATIONS
window.addEventListener("offline", function(e) { log("Offline");
}, true);
Manifest Files
Offline applications consist of a manifest listing one or more resources that browser will cache for offline use. Manifest files have the MIME type text/cache-manifest. The SimpleHTTPServer module in the Python standard library will serve files with the .manifest extension with the header Content-type: text/cache-manifest. To configure settings, open the file PYTHON_HOME/Lib/mimetypes.py, and add the following line:
'.appcache' |
: 'text/cache-manifest manifest', |
Other web servers may require additional configuration. For example, for Apache HTTP Server, you can update the mime.types file in the conf folder by adding the following line:
text/cache-manifest appcache
If you are using Microsoft IIS, in your website’s home, double-click the MIME Types icon, then add the .appcache extension with MIME type text/cache-manifest in the Add MIME Type dialog.
The manifest syntax is simple line separated text that starts with CACHE MANIFEST (as the first line). Lines can end in CR, LF, or CRLF—the format is flexible—but the text must be UTF-8 encoded, which is the typical output for most text editors. Comments begin with the hash symbol and must be on their own lines; you cannot append a comment to other non-comment lines in the file.
Listing 12-5. Example Manifest File with All Possible Sections
CACHE MANIFEST
# files to cache about.html html5.css index.html happy-trails-rc.gif lake-tahoe.JPG
#do not cache signup page NETWORK
signup.html
FALLBACK
signup.html offline.html /app/ajax/ default.html
Let’s look at the different sections.
If no CACHE: heading is specified, the files that are listed will be treated as files to be cached (caching is the default behavior). The following simple manifest specifies that three files (index.html, application.js, and style.css) must be cached:
CACHE MANIFEST index.html application.js
299
CHAPTER 12 ■ CREATING OFFLINE WEB APPLICATIONS
style.css
Similarly, the following section would do the same (you can use the same CACHE, NETWORK, and FALLBACK headers multiple times in a manifest file if you want to):
CACHE MANIFEST
# Cache section CACHE: Index.html application.js style.css
By listing a file in the CACHE section, you instruct the browser to serve the file from the application cache, even if the application is online. It is unnecessary to specify the application's main HTML resource. The HTML document that initially pointed to the manifest file is implicitly included (this is called a Master entry). However, if you want to cache multiple HTML documents or if you would like multiple HTML documents to act as possible entry points for the cacheable application, they should all be explicitly listed in the cache manifest file.
FALLBACK entries allow you to give alternate paths to replace resources that cannot be fetched. The manifest in Listing 12-5 would cause requests to /app/ajax/ or subpaths beginning with /app/ajax/ to fall back to default.html when /app/ajax/* is unreachable.
NETWORK specifies resources that are always fetched using the network. The difference with simply omitting these files from the manifest is that master entries are cached without being explicitly listed in the manifest file. To ensure that the application requests the file from the server even if the cached resource is cached in the application cache, you can place that file in the NETWORK: section.
The ApplicationCache API
The ApplicationCache API is an interface for working with the application cache. A new window.applicationCache object fires several events related to the state of the cache. The object has a numerical property, window.applicationCache.status, which indicates the state of the cache. The six states a cache can have are shown in Table 12-1.
Table 12-1. The Six Cache States
Numerical Cache Status
Property
0UNCACHED
1IDLE
2CHECKING
3DOWNLOADING
4UPDATEREADY
5OBSOLETE
Most pages on the Web today do not specify cache manifests and are uncached. Idle is the typical state for an application with a cache manifest. An application in the idle state has all its resources stored
300