Knockout JS: Helping you build dynamic JavaScript UIs with MVVM and ASP.NET

Introduction

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

Headline features:

  • Elegant dependency tracking – automatically updates the right parts of your UI whenever your data model changes.
  • Declarative bindings – a simple and obvious way to connect parts of your UI to your data model. You can construct a complex dynamic UIs easily using arbitrarily nested binding contexts.
  • Trivially extensible – implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code.

Additional benefits:

  • Pure JavaScript library – works with any server or client-side technology
  • Can be added on top of your existing web application without requiring major architectural changes
  • Compact – around 13kb after gzipping
  • Works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, others)
  • Comprehensive suite of specifications (developed BDD-style) means its correct functioning can easily be verified on new browsers and platforms

Developers familiar with Ruby on Rails, ASP.NET MVC, or other MV* technologies may see MVVM as a real-time form of MVC with declarative syntax. In another sense, you can think of KO as a general way to make UIs for editing JSON data… whatever works for you 🙂

OK, how do you use it?

The quickest and most fun way to get started is by working through the interactive tutorials. Once you’ve got to grips with the basics, explore the live examples and then have a go with it in your own project.

Is KO intended to compete with jQuery (or Prototype, etc.) or work with it?

Everyone loves jQuery! It’s an outstanding replacement for the clunky, inconsistent DOM API we had to put up with in the past. jQuery is an excellent low-level way to manipulate elements and event handlers in a web page. KO solves a different problem.

As soon as your UI gets nontrivial and has a few overlapping behaviors, things can get tricky and expensive to maintain if you only use jQuery. Consider an example: you’re displaying a list of items, stating the number of items in that list, and want to enable an ‘Add’ button only when there are fewer than 5 items. jQuery doesn’t have a concept of an underlying data model, so to get the number of items you have to infer it from the number of TRs in a table or the number of DIVs with a certain CSS class. Maybe the number of items is displayed in some SPAN, and you have to remember to update that SPAN’s text when the user adds an item. You also must remember to disable the ‘Add’ button when the number of TRs is 5. Later, you’re asked also to implement a ‘Delete’ button and you have to figure out which DOM elements to change whenever it’s clicked.

How is Knockout different?

It’s much easier with KO. It lets you scale up in complexity without fear of introducing inconsistencies. Just represent your items as a JavaScript array, and then use a foreach binding to transform this array into a TABLE or set of DIVs. Whenever the array changes, the UI changes to match (you don’t have to figure out how to inject new TRs or where to inject them). The rest of the UI stays in sync. For example, you can declaratively bind a SPAN to display the number of items as follows:

There are <span data-bind="text: myItems().count"></span> items

That’s it! You don’t have to write code to update it; it updates on its own when the myItems array changes. Similarly, to make the ‘Add’ button enable or disable depending on the number of items, just write:

<button data-bind="enable: myItems().count < 5">Add</button>

Later, when you’re asked to implement the ‘Delete’ functionality, you don’t have to figure out what bits of the UI it has to interact with; you just make it alter the underlying data model.

To summarise: KO doesn’t compete with jQuery or similar low-level DOM APIs. KO provides a complementary, high-level way to link a data model to a UI. KO itself doesn’t depend on jQuery, but you can certainly use jQuery at the same time, and indeed that’s often useful if you want things like animated transitions.

Knockout JS: Helping you build dynamic JavaScript UIs with MVVM and ASP.NET

Reference : http://knockoutjs.com/documentation/introduction.html

Introduction to SignalR

ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

SignalR can be used to add any sort of “real-time” web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see new data, or the page implements long polling to retrieve new data, it is a candidate for using SignalR. Examples include dashboards and monitoring applications, collaborative applications (such as simultaneous editing of documents), job progress updates, and real-time forms.

SignalR also enables completely new types of web applications that require high frequency updates from the server, for example, real-time gaming. For a great example of this, see the ShootR game.

SignalR provides a simple API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers (and other client platforms) from server-side .NET code. SignalR also includes API for connection management (for instance, connect and disconnect events), and grouping connections.

Invoking methods with SignalR

SignalR handles connection management automatically, and lets you broadcast messages to all connected clients simultaneously, like a chat room. You can also send messages to specific clients. The connection between the client and server is persistent, unlike a classic HTTP connection, which is re-established for each communication.

SignalR supports “server push” functionality, in which server code can call out to client code in the browser using Remote Procedure Calls (RPC), rather than the request-response model common on the web today.

SignalR applications can scale out to thousands of clients using Service Bus, SQL Server or Redis.

SignalR is open-source, accessible through GitHub.

SignalR and WebSocket

SignalR uses the new WebSocket transport where available, and falls back to older transports where necessary. While you could certainly write your application using WebSocket directly, using SignalR means that a lot of the extra functionality you would need to implement will already have been done for you. Most importantly, this means that you can code your application to take advantage of WebSocket without having to worry about creating a separate code path for older clients. SignalR also shields you from having to worry about updates to WebSocket, since SignalR will continue to be updated to support changes in the underlying transport, providing your application a consistent interface across versions of WebSocket.

While you could certainly create a solution using WebSocket alone, SignalR provides all of the functionality you would need to write yourself, such as fallback to other transports and revising your application for updates to WebSocket implementations.

Transports and fallbacks

SignalR is an abstraction over some of the transports that are required to do real-time work between client and server. A SignalR connection starts as HTTP, and is then promoted to a WebSocket connection if it is available. WebSocket is the ideal transport for SignalR, since it makes the most efficient use of server memory, has the lowest latency, and has the most underlying features (such as full duplex communication between client and server), but it also has the most stringent requirements: WebSocket requires the server to be using Windows Server 2012 or Windows 8, and .NET Framework 4.5. If these requirements are not met, SignalR will attempt to use other transports to make its connections.

HTML 5 transports

These transports depend on support for HTML 5. If the client browser does not support the HTML 5 standard, older transports will be used.

  • WebSocket (if the both the server and browser indicate they can support Websocket). WebSocket is the only transport that establishes a true persistent, two-way connection between client and server. However, WebSocket also has the most stringent requirements; it is fully supported only in the latest versions of Microsoft Internet Explorer, Google Chrome, and Mozilla Firefox, and only has a partial implementation in other browsers such as Opera and Safari.
  • Server Sent Events, also known as EventSource (if the browser supports Server Sent Events, which is basically all browsers except Internet Explorer.)

Comet transports

The following transports are based on the Comet web application model, in which a browser or other client maintains a long-held HTTP request, which the server can use to push data to the client without the client specifically requesting it.

  • Forever Frame (for Internet Explorer only). Forever Frame creates a hidden IFrame which makes a request to an endpoint on the server that does not complete. The server then continually sends script to the client which is immediately executed, providing a one-way realtime connection from server to client. The connection from client to server uses a separate connection from the server to client connection, and like a standard HTML request, a new connection is created for each piece of data that needs to be sent.
  • Ajax long polling. Long polling does not create a persistent connection, but instead polls the server with a request that stays open until the server responds, at which point the connection closes, and a new connection is requested immediately. This may introduce some latency while the connection resets.

For more information on what transports are supported under which configurations, see Supported Platforms.

Monitoring transports

You can determine what transport your application is using by enabling logging on your hub, and opening the console window in your browser.

To enable logging for your hub’s events in a browser, add the following command to your client application:

$.connection.myHub.logging = true;

  • In Internet Explorer, open the developer tools by pressing F12, and click the Console tab.Console in Microsoft Internet Explorer
  • In Chrome, open the console by pressing Ctrl+Shift+J.Console in Google Chrome

With the console open and logging enabled, you’ll be able to see which transport is being used by SignalR.

Console in Internet Explorer showing WebSocket transport

Specifying a transport

Negotiating a transport takes a certain amount of time and client/server resources. If the client capabilities are known, then a transport can be specified when the client connection is started. The following code snippet demonstrates starting a connection using the Ajax Long Polling transport, as would be used if it was known that the client did not support any other protocol:

connection.start({ transport: 'longPolling' });

You can specify a fallback order if you want a client to try specific transports in order. The following code snippet demonstrates trying WebSocket, and failing that, going directly to Long Polling.

connection.start({ transport: ['webSockets','longPolling'] });

The string constants for specifying transports are defined as follows:

  • webSockets
  • forverFrame
  • serverSentEvents
  • longPolling

Connections and Hubs

The SignalR API contains two models for communicating between clients and servers: Persistent Connections and Hubs.

A Connection represents a simple endpoint for sending single-recipient, grouped, or broadcast messages. The Persistent Connection API (represented in .NET code by the PersistentConnection class) gives the developer direct access to the low-level communication protocol that SignalR exposes. Using the Connections communication model will be familiar to developers who have used connection-based APIs such as Windows Communcation Foundation.

A Hub is a more high-level pipeline built upon the Connection API that allows your client and server to call methods on each other directly. SignalR handles the dispatching across machine boundaries as if by magic, allowing clients to call methods on the server as easily as local methods, and vice versa. Using the Hubs communication model will be familiar to developers who have used remote invocation APIs such as .NET Remoting. Using a Hub also allows you to pass strongly typed parameters to methods, enabling model binding.

Architecture diagram

The following diagram shows the relationship between Hubs, Persistent Connections, and the underlying technologies used for transports.

SignalR Architecture Diagram showing APIs, transports, and clients

How Hubs work

When server-side code calls a method on the client, a packet is sent across the active transport that contains the name and parameters of the method to be called (when an object is sent as a method parameter, it is serialized using JSON). The client then matches the method name to methods defined in client-side code. If there is a match, the client method will be executed using the deserialized parameter data.

The method call can be monitored using tools like Fiddler. The following image shows a method call sent from a SignalR server to a web browser client in the Logs pane of Fiddler. The method call is being sent from a hub calledMoveShapeHub, and the method being invoked is called updateShape.

View of Fiddler log showing SignalR traffic

In this example, the hub name is identified with the H parameter; the method name is identified with the Mparameter, and the data being sent to the method is identified with the A parameter. The application that generated this message is created in the High-Frequency Realtime tutorial.

Choosing a communication model

Most applications should use the Hubs API. The Connections API could be used in the following circumstances:

  • The format of the actual message sent needs to be specified.
  • The developer prefers to work with a messaging and dispatching model rather than a remote invocation model.
  • An existing application that uses a messaging model is being ported to use SignalR.

Reference : http://www.asp.net/signalr/overview/getting-started/introduction-to-signalr

Comet Programming: the Hidden IFrame Technique

As covered in Comet Programming: Using Ajax to Simulate Server Push, Comet is a Web application model that enables Web servers to send data to the client without having to explicitly request it. Hence, the Comet model provides an alternate mechanism to classical polling to update page content and/or data. In that article, we learned how to use XMLHttpRequest long polling to refresh page components and keep cached data in synch with the server. Another Comet strategy, sometimes referred to as the “Forever Frame” technique, is to use a hidden IFrame. As with XMLHttpRequest long polling, the “Forever Frame” technique also relies on browser-native technologies, rather than on proprietary plugins or other special technologies.

IFrames Technique Overview

IFrame stands for Inline Frame. It allows a Web page to embed one HTML document inside another HTML element. As you can imagine, it’s a simple way to create a “mashup”, whereby the page combines data from several sources into a single integrated document:

1 <html>
2 <head>
3 <title>IFrames Example</title>
4 <meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
5 </head>
6 <body bgcolor=”#FFFFFF” id=body>
7 <h2 align=”center”>IFrames Example</h2>
8         The content below comes from the website http://www.robgravelle.com
9         <iframe src=”http://www.robgravelle.com/” height=”200″&gt;
10             Your browsers does not support IFrames.
11         </iframe>
12 </body>
13 </html>
view plain | print | ?

Normally, data delivered in HTTP responses is sent in one piece. The length of the data is indicated by theContent-Length header field. With chunked encoding, the data is broken up into a series of blocks of data and transmitted in one or more “chunks” so that a server may start sending data before it knows the final size of the content that it’s sending. Note that the size of the blocks may or may not be the same:

1 HTTP/1.1 200 OK
2 Content-Type: text/plain
3 Transfer-Encoding: chunked
4 23
5 This is the data in the first chunk
6 1A
7 and this is the second one
8 0
view plain | print | ?

In Forever Frame Streaming, a series of JavaScript commands is sent to a hidden IFrame as a chunked block. As events occur, the IFrame is gradually filled with script tags, containing JavaScript to be executed in the browser. Because browsers render HTML pages incrementally, each script tag is executed as it is received.

Two benefits of the IFrame method are that it’s fairly easy to implement and it works in every common browser. On the cons side, there is no way to handle errors reliably nor is it possible to track the state of the request calling process. Therefore, if you want to track the progress of the request, you’d best stick with the XMLHttpRequest method.

Continue reading

Comet (programming)

Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it.[1][2] Comet is an umbrella term, encompassing multiple techniques for achieving this interaction. All these methods rely on features included by default in browsers, such as JavaScript, rather than on non-default plugins. The Comet approach differs from the original model of the web, in which a browser requests a complete web page at a time.[3]

The use of Comet techniques in web development predates the use of the word Comet as a neologism for the collective techniques. Comet is known by several other names, including Ajax Push,[4][5]Reverse Ajax,[6] Two-way-web,[7] HTTP Streaming,[7] and HTTP server push[8] among others.[9]

Implementations

Comet applications attempt to eliminate the limitations of the page-by-page web model and traditional polling by offering real-time interaction, using a persistent or long-lasting HTTP connection between the server and the client. Since browsers and proxies are not designed with server events in mind, several techniques to achieve this have been developed, each with different benefits and drawbacks. The biggest hurdle is the HTTP 1.1 specification, which states that a browser should not have more than two simultaneous connections with a web server.[10] Therefore, holding one connection open for real-time events has a negative impact on browser usability: the browser may be blocked from sending a new request while waiting for the results of a previous request, e.g., a series of images. This can be worked around by creating a distinct hostname for real-time information, which is an alias for the same physical server.

Specific methods of implementing Comet fall into two major categories: streaming and long polling.

 

Reference : http://en.wikipedia.org/wiki/Comet_%28programming%29

Ajax IM — Instant Messaging framework

What is Ajax IM?

Ajax IM (“Ajax Instant Messenger”) is a browser-centric instant messaging framework. It uses AJAX to create a real-time (or near real-time) IM environment that can be used in conjunction with existing community and commercial software, or simply as a stand-alone product.

Ajax IM has been truly rebuilt from the bot­tom up, imple­ment­ing the lat­est libraries, tech­niques, and shini­ness includ­ing jQuery, local ses­sion stor­age (using HTML5 or Flash), Node.js, and much more.

Installation.

Let’s get you set up, shall we?

By default, there are two choices for installation: thePHP-based or standalone servers. While thestandalone server is recommended for scaling and extensibility, it requires you to be on a VPS or dedicated server. On the other hand, the PHP-basedserver does not have this requirement, though it is recommended that you use a server other than Apache in this case

Step 1 — Extract

After downloading the latest version, extract the archive into its own folder. Upload all included files to your server.

Step 2 — Configure and Install

Change the permissions for config.php andjs/im.js to 755 (writable). Additionally, if you plan on using a library that uses the standalone Node.js server (NodeJS or NodeJS Guests), set the permissions for node/config.js to 755 as well. The install script will need to alter these files during installation (unless you handle installation manually).

In your browser, navigate to install.php in the folder where you uploaded Ajax IM (e.g.,http://yoursite.com/ajaxim/install.php). The installer will guide you through the steps and configuration options for setting up Ajax IM, the database (if necessary), and the standalone server (if necessary).

Note: After completing installation, deleteinstall.php.

config.php     →   0755 (rwxrw-rw--)
js/
 ↳ im.js       →   0755 (rwxrw-rw--)
node/
 ↳ config.js   →   0755 (rwxrw-rw--)

Step 3 — Implement

To use Ajax IM on your website, you’ll only need to manually include the im.load.js script in your pages. The script will automatically test for and include any of the dependencies and the main Ajax IM library.

If you’re using the included MySQL database engine and the Default or NodeJS server libraries, you should read either the Quick Start with PHP or Quick Start with Node.js guides.

<script type="text/javascript"
   src="ajaxim/js/im.load.js"></script>

Step 4 — Finished

That’s it! There really isn’t anything more to the installation.

For more information about integrating Ajax IM with your database, take a look at the documentation; also be sure to check out the add-ons (coming soon) page for alternative server scripts, database engines, and modifications.

Reference : http://ajaxim.com/installation/

 

 

Detecting HTML5 Features

DIVING IN

You may well ask: “How can I start using HTML5 if older browsers don’t support it?” But the question itself is misleading. HTML5 is not one big thing; it is a collection of individual features. So you can’t detect “HTML5support,” because that doesn’t make any sense. But you can detect support for individual features, like canvas, video, or geolocation.

DETECTION TECHNIQUES

When your browser renders a web page, it constructs a Document Object Model (DOM), a collection of objects that represent the HTML elements on the page. Every element — every <p>, every <div>, every <span> — is represented in the DOM by a different object. (There are also global objects, like window and document, that aren’t tied to specific elements.)

girl peeking out the window

All DOM objects share a set of common properties, but some objects have more than others. In browsers that support HTML5 features, certain objects will have unique properties. A quick peek at the DOM will tell you which features are supported.

There are four basic techniques for detecting whether a browser supports a particular feature. From simplest to most complex:

  1. Check if a certain property exists on a global object (such as window ornavigator).

    Example: testing for geolocation support

  2. Create an element, then check if a certain property exists on that element.

    Example: testing for canvas support

  3. Create an element, check if a certain method exists on that element, then call the method and check the value it returns.

    Example: testing which video formats are supported

  4. Create an element, set a property to a certain value, then check if the property has retained its value.

    Example: testing which <input> types are supported

MODERNIZR, AN HTML5 DETECTION LIBRARY

Modernizr is an open source, MIT-licensed JavaScript library that detects support for many HTML5 & CSS3 features. At the time of writing, the latest version is 1.5. You should always use the latest version. To use it, include the following <script>element at the top of your page.

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dive Into HTML5</title> <script src="modernizr.min.js"></script> </head> <body> ... </body> </html> 

↜ It goes to your <head>

Modernizr runs automatically. There is no modernizr_init() function to call. When it runs, it creates a global object calledModernizr, that contains a set of Boolean properties for each feature it can detect. For example, if your browser supports thecanvas API, the Modernizr.canvas property will be true. If your browser does not support the canvas API, theModernizr.canvas property will be false.

if (Modernizr.canvas) { // let's draw some shapes! } else { // no native canvas support available :( }

CANVAS

man fishing in a canoe
Your browser supports the canvas API.

HTML5 defines the <canvas> element as “a resolution-dependent bitmap canvas that can be used for rendering graphs, game graphics, or other visual images on the fly.” A canvas is a rectangle in your page where you can use JavaScript to draw anything you want. HTML5 defines a set of functions (“the canvas API”) for drawing shapes, defining paths, creating gradients, and applying transformations.

Checking for the canvas API uses detection technique #2. If your browser supports the canvas API, the DOM object it creates to represent a <canvas> element will have a getContext() method. If your browser doesn’t support the canvas API, theDOM object it creates for a <canvas> element will only have the set of common properties, but not anything canvas-specific.

function supports_canvas() { return !!document.createElement('canvas').getContext; } 

This function starts by creating a dummy <canvas> element. But the element is never attached to your page, so no one will ever see it. It’s just floating in memory, going nowhere and doing nothing, like a canoe on a lazy river.

return !!document.createElement('canvas').getContext;

As soon as you create the dummy <canvas> element, you test for the presence of a getContext() method. This method will only exist if your browser supports the canvas API.

return !!document.createElement('canvas').getContext;

Finally, you use the double-negative trick to force the result to a Boolean value (true or false).

return !!document.createElement('canvas').getContext;

This function will detect support for most of the canvas API, including shapespathsgradients & patterns. It will not detect the third-party explorercanvas library that implements the canvas API in Microsoft Internet Explorer.

Instead of writing this function yourself, you can use Modernizr to detect support for the canvas API.

↶ check for canvas support

if (Modernizr.canvas) { // let's draw some shapes! } else { // no native canvas support available :( }

There is a separate test for the canvas text API, which I will demonstrate next.

CANVAS TEXT

baseball player at bat
Your browser supports the canvas text API.

Even if your browser supports the canvas API, it might not support the canvas text API. The canvas API grew over time, and the text functions were added late in the game. Some browsers shipped with canvas support before the text API was complete.

Checking for the canvas text API uses detection technique #2. If your browser supports the canvas API, the DOM object it creates to represent a <canvas> element will have the getContext() method. If your browser doesn’t support the canvas API, the DOM object it creates for a <canvas> element will only have the set of common properties, but not anything canvas-specific.

function supports_canvas_text() { if (!supports_canvas()) { return false; } var dummy_canvas = document.createElement('canvas'); var context = dummy_canvas.getContext('2d'); return typeof context.fillText == 'function'; }

The function starts by checking for canvas support, using the supports_canvas() function you just saw in the previous section. If your browser doesn’t support the canvas API, it certainly won’t support the canvas text API!

if (!supports_canvas()) { return false; }

Next, you create a dummy <canvas> element and get its drawing context. This is guaranteed to work, because thesupports_canvas() function already checked that the getContext() method exists on all canvas objects.

var dummy_canvas = document.createElement('canvas'); var context = dummy_canvas.getContext('2d');

Finally, you check whether the drawing context has a fillText() function. If it does, the canvas text API is available. Hooray!

return typeof context.fillText == 'function';

Instead of writing this function yourself, you can use Modernizr to detect support for the canvas text API.

↶ check for canvas text support

if (Modernizr.canvastext) { // let's draw some text! } else { // no native canvas text support available :( }

VIDEO

HTML5 defines a new element called <video> for embedding video in your web pages. Embedding video used to be impossible without third-party plugins such as Apple QuickTime® or Adobe Flash®.

audience at the theater
Your browser supports HTML5 video.

The <video> element is designed to be usable without any detection scripts. You can specify multiple video files, and browsers that support HTML5 video will choose one based on what video formats they support. (See “A gentle introduction to video encoding” part 1: container formats and part 2: lossy video codecs to learn about different video formats.)

Browsers that don’t support HTML5 video will ignore the <video> element completely, but you can use this to your advantage and tell them to play video through a third-party plugin instead. Kroc Camen has designed a solution called Video for Everybody! that uses HTML5video where available, but falls back to QuickTime or Flash in older browsers. This solution uses no JavaScript whatsoever, and it works in virtually every browser, including mobile browsers.

If you want to do more with video than plop it on your page and play it, you’ll need to use JavaScript. Checking for video support uses detection technique #2. If your browser supportsHTML5 video, the DOM object it creates to represent a <video> element will have acanPlayType() method. If your browser doesn’t support HTML5 video, the DOM object it creates for a <video> element will have only the set of properties common to all elements. You can check for video support using this function:

function supports_video() { return !!document.createElement('video').canPlayType; }

Instead of writing this function yourself, you can use Modernizr to detect support for HTML5 video.

↶ check for HTML5 video support

if (Modernizr.video) { // let's play some video! } else { // no native video support available :( // maybe check for QuickTime or Flash instead }

In the Video chapter, I’ll explain another solution that uses these detection techniques to convert <video> elements to Flash-based video players, for the benefit of browsers that don’t support HTML5 video.

There is a separate test for detecting which video formats your browser can play, which I will demonstrate next.

VIDEO FORMATS

Video formats are like written languages. An English newspaper may convey the same information as a Spanish newspaper, but if you can only read English, only one of them will be useful to you! To play a video, your browser needs to understand the “language” in which the video was written.

man reading newspaper
Your browser can play both Ogg Theora and H.264 video. Hey, you can play WebM video, too!

The “language” of a video is called a “codec” — this is the algorithm used to encode the video into a stream of bits. There are dozens of codecs in use all over the world. Which one should you use? The unfortunate reality of HTML5 video is that browsers can’t agree on a single codec. However, they seem to have narrowed it down to two. One codec costs money (because of patent licensing), but it works in Safari and on the iPhone. (This one also works in Flash if you use a solution like Video for Everybody!) The other codec is free and works in open source browsers like Chromium and Mozilla Firefox.

Checking for video format support uses detection technique #3. If your browser supportsHTML5 video, the DOM object it creates to represent a <video> element will have acanPlayType() method. This method will tell you whether the browser supports a particular video format.

This function checks for the patent-encumbered format supported by Macs and iPhones.

function supports_h264_baseline_video() { if (!supports_video()) { return false; } var v = document.createElement("video"); return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'); }

The function starts by checking for HTML5 video support, using the supports_video() function you just saw in the previous section. If your browser doesn’t support HTML5 video, it certainly won’t support any video formats!

if (!supports_video()) { return false; }

Then the function creates a dummy <video> element (but doesn’t attach it to the page, so it won’t be visible) and calls thecanPlayType() method. This method is guaranteed to be there, because the supports_video() function just checked for it.

var v = document.createElement("video");

A “video format” is really a combination of different things. In technical terms, you’re asking the browser whether it can play H.264 Baseline video and AAC LC audio in an MPEG-4 container. (I’ll explain what all that means in the Video chapter. You might also be interested in reading A gentle introduction to video encoding.)

return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');

The canPlayType() function doesn’t return true or false. In recognition of how complex video formats are, the function returns a string:

  • "probably" if the browser is fairly confident it can play this format
  • "maybe" if the browser thinks it might be able to play this format
  • "" (an empty string) if the browser is certain it can’t play this format

This second function checks for the open video format supported by Mozilla Firefox and other open source browsers. The process is exactly the same; the only difference is the string you pass in to the canPlayType() function. In technical terms, you’re asking the browser whether it can play Theora video and Vorbis audio in an Ogg container.

function supports_ogg_theora_video() { if (!supports_video()) { return false; } var v = document.createElement("video"); return v.canPlayType('video/ogg; codecs="theora, vorbis"'); }

Finally, WebM is a newly open-sourced (and non-patent-encumbered) video codec that will be included in the next version of major browsers, including Chrome, Firefox, and Opera. You can use the same technique to detect support for open WebM video.

function supports_webm_video() { if (!supports_video()) { return false; } var v = document.createElement("video"); return v.canPlayType('video/webm; codecs="vp8, vorbis"'); }

Instead of writing this function yourself, you can use Modernizr (1.5 or later) to detect support for different HTML5 video formats.

↶ check for HTML5 video formats

if (Modernizr.video) { // let's play some video! but what kind? if (Modernizr.video.webm) { // try WebM } else if (Modernizr.video.ogg) { // try Ogg Theora + Vorbis in an Ogg container } else if (Modernizr.video.h264){ // try H.264 video + AAC audio in an MP4 container } }

LOCAL STORAGE

filing cabinet with drawers of different sizes
Your browser supports HTML5 storage.

HTML5 storage provides a way for web sites to store information on your computer and retrieve it later. The concept is similar to cookies, but it’s designed for larger quantities of information. Cookies are limited in size, and your browser sends them back to the web server every time it requests a new page (which takes extra time and precious bandwidth). HTML5 storage stays on your computer, and web sites can access it with JavaScript after the page is loaded.

ASK PROFESSOR MARKUP

☞Q: Is local storage really part of HTML5? Why is it in a separate specification?
A: The short answer is yes, local storage is part of HTML5. The slightly longer answer is that local storage used to be part of the main HTML5 specification, but it was split out into a separate specification because some people in theHTML5 Working Group complained that HTML5 was too big. If that sounds like slicing a pie into more pieces to reduce the total number of calories… well, welcome to the wacky world of standards.

Checking for HTML5 storage support uses detection technique #1. If your browser supports HTML5 storage, there will be alocalStorage property on the global window object. If your browser doesn’t support HTML5 storage, the localStorageproperty will be undefined. Due to an unfortunate bug in older versions of Firefox, this test will raise an exception if cookies are disabled, so the entire test is wrapped in a try..catch statement.

function supports_local_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch(e){ return false; } }

Instead of writing this function yourself, you can use Modernizr (1.1 or later) to detect support for HTML5 local storage.

↶ check for HTML5 local storage

if (Modernizr.localstorage) { // window.localStorage is available! } else { // no native support for local storage :( // maybe try Gears or another third-party solution }

Note that JavaScript is case-sensitive. The Modernizr attribute is called localstorage (all lowercase), but the DOM property is called window.localStorage (mixed case).

ASK PROFESSOR MARKUP

☞Q: How secure is my HTML5 storage database? Can anyone read it?
A: Anyone who has physical access to your computer can probably look at (or even change) your HTML5 storage database. Within your browser, any web site can read and modify its own values, but sites can’t access values stored by other sites. This is called a same-origin restriction.

WEB WORKERS

Your browser supports web workers.

Web Workers provide a standard way for browsers to run JavaScript in the background. With web workers, you can spawn multiple “threads” that all run at the same time, more or less. (Think of how your computer can run multiple applications at the same time, and you’re most of the way there.) These “background threads” can do complex mathematical calculations, make network requests, or access local storage while the main web page responds to the user scrolling, clicking, or typing.

Checking for web workers uses detection technique #1. If your browser supports the Web Worker API, there will be a Workerproperty on the global window object. If your browser doesn’t support the Web Worker API, the Worker property will be undefined.

function supports_web_workers() { return !!window.Worker; }

Instead of writing this function yourself, you can use Modernizr (1.1 or later) to detect support for web workers.

↶ check for web workers

if (Modernizr.webworkers) { // window.Worker is available! } else { // no native support for web workers :( // maybe try Gears or another third-party solution }

Note that JavaScript is case-sensitive. The Modernizr attribute is called webworkers (all lowercase), but the DOM object is called window.Worker (with a capital “W” in “Worker”).

OFFLINE WEB APPLICATIONS

cabin in the woods
Your browser supports offline web applications.

Reading static web pages offline is easy: connect to the Internet, load a web page, disconnect from the Internet, drive to a secluded cabin, and read the web page at your leisure. (To save time, you may wish to skip the step about the cabin.) But what about web applications like Gmail or Google Docs? Thanks to HTML5, anyone (not just Google!) can build a web application that works offline.

Offline web applications start out as online web applications. The first time you visit an offline-enabled web site, the web server tells your browser which files it needs in order to work offline. These files can be anything — HTML, JavaScript, images, even videos. Once your browser downloads all the necessary files, you can revisit the web site even if you’re not connected to the Internet. Your browser will notice that you’re offline and use the files it has already downloaded. When you get back online, any changes you’ve made can be uploaded to the remote web server.

Checking for offline support uses detection technique #1. If your browser supports offline web applications, there will be anapplicationCache property on the global window object. If your browser doesn’t support offline web applications, theapplicationCache property will be undefined. You can check for offline support with the following function:

function supports_offline() { return !!window.applicationCache; }

Instead of writing this function yourself, you can use Modernizr (1.1 or later) to detect support for offline web applications.

↶ check for offline support

if (Modernizr.applicationcache) { // window.applicationCache is available! } else { // no native support for offline :( // maybe try Gears or another third-party solution }

Note that JavaScript is case-sensitive. The Modernizr attribute is called applicationcache (all lowercase), but the DOMobject is called window.applicationCache (mixed case).

GEOLOCATION

Geolocation is the art of figuring out where you are in the world and (optionally) sharing that information with people you trust. There is more than one way to figure out where you are — your IP address, your wireless network connection, which cell tower your phone is talking to, or dedicated GPS hardware that calculates latitude and longitude from information sent by satellites in the sky.

man with a globe for a head
Your browser supports geolocation. Click to look up your location.

ASK PROFESSOR MARKUP

☞Q: Is geolocation part of HTML5? Why are you talking about it?
A: Geolocation support is being added to browsers right now, along with support for new HTML5 features. Strictly speaking, geolocation is being standardized by the Geolocation Working Group, which is separate from theHTML5 Working Group. But I’m going to talk about geolocation in this book anyway, because it’s part of the evolution of the web that’s happening now.

Checking for geolocation support uses detection technique #1. If your browser supports the geolocation API, there will be ageolocation property on the global navigator object. If your browser doesn’t support the geolocation API, the geolocationproperty will be undefined. Here’s how to check for geolocation support:

function supports_geolocation() { return !!navigator.geolocation; }

Instead of writing this function yourself, you can use Modernizr to detect support for the geolocation API.

↶ check for geolocation support

if (Modernizr.geolocation) { // let's find out where you are! } else { // no native geolocation support available :( // maybe try Gears or another third-party solution }

If your browser does not support the geolocation API natively, there is still hope. Gears is an open source browser plugin from Google that works on Windows, Mac, Linux, Windows Mobile, and Android. It provides features for older browsers that do not support all the fancy new stuff we’ve discussed in this chapter. One of the features that Gears provides is a geolocation API. It’s not the same as the navigator.geolocation API, but it serves the same purpose.

There are also device-specific geolocation APIs on older mobile phone platforms, including BlackBerryNokiaPalm, andOMTP BONDI.

The chapter on geolocation will go into excruciating detail about how to use all of these different APIs.

INPUT TYPES

manual typewriter
Your browser supports the following HTML5 input types: searchtel,urlemailnumberrange

You know all about web forms, right? Make a <form>, add a few <input type="text">elements and maybe an <input type="password">, and finish it off with an <input type="submit"> button.

You don’t know the half of it. HTML5 defines over a dozen new input types that you can use in your forms.

  1. <input type="search"> for search boxes
  2. <input type="number"> for spinboxes
  3. <input type="range"> for sliders
  4. <input type="color"> for color pickers
  5. <input type="tel"> for telephone numbers
  6. <input type="url"> for web addresses
  7. <input type="email"> for email addresses
  8. <input type="date"> for calendar date pickers
  9. <input type="month"> for months
  10. <input type="week"> for weeks
  11. <input type="time"> for timestamps
  12. <input type="datetime"> for precise, absolute date+time stamps
  13. <input type="datetime-local"> for local dates and times

Checking for HTML5 input types uses detection technique #4. First, you create a dummy <input> element in memory. The default input type for all <input> elements is "text". This will prove to be vitally important.

var i = document.createElement("input");

Next, set the type attribute on the dummy <input> element to the input type you want to detect.

i.setAttribute("type", "color");

If your browser supports that particular input type, the type property will retain the value you set. If your browser doesn’t support that particular input type, it will ignore the value you set and the type property will still be "text".

return i.type !== "text";

Instead of writing 13 separate functions yourself, you can use Modernizr to detect support for all the new input types defined in HTML5. Modernizr reuses a single <input> element to efficiently detect support for all 13 input types. Then it builds a hash called Modernizr.inputtypes, that contains 13 keys (the HTML5 type attributes) and 13 Boolean values (true if supported, false if not).

↶ check for native date picker

if (!Modernizr.inputtypes.date) { // no native support for <input type="date"> :( // maybe build one yourself with Dojo or jQueryUI }

PLACEHOLDER TEXT

Besides new input typesHTML5 includes several small tweaks to existing forms. One improvement is the ability to set placeholder text in an input field. Placeholder text is displayed inside the input field as long as the field is empty and not focused. As soon you click on (or tab to) the input field, the placeholder text disappears. The chapter on web forms has screenshots if you’re having trouble visualizing it.

Checking for placeholder support uses detection technique #2. If your browser supports placeholder text in input fields, theDOM object it creates to represent an <input> element will have a placeholder property (even if you don’t include aplaceholder attribute in your HTML). If your browser doesn’t support placeholder text, the DOM object it creates for an<input> element will not have a placeholder property.

function supports_input_placeholder() { var i = document.createElement('input'); return 'placeholder' in i; }

Instead of writing this function yourself, you can use Modernizr (1.1 or later) to detect support for placeholder text.

↶ check for placeholder text

if (Modernizr.input.placeholder) { // your placeholder text should already be visible! } else { // no placeholder support :( // fall back to a scripted solution }

FORM AUTOFOCUS

angry guy with arms up
Your browser supports form autofocus.

Web sites can use JavaScript to focus the first input field of a web form automatically. For example, the home page of Google.com will autofocus the input box so you can type your search keywords without having to position the cursor in the search box. While this is convenient for most people, it can be annoying for power users or people with special needs. If you press the space bar expecting to scroll the page, the page will not scroll because the focus is already in a form input field. (It types a space in the field instead of scrolling.) If you focus a different input field while the page is still loading, the site’s autofocus script may “helpfully” move the focus back to the original input field upon completion, disrupting your flow and causing you to type in the wrong place.

Because the autofocusing is done with JavaScript, it can be tricky to handle all of these edge cases, and there is little recourse for people who don’t want a web page to “steal” the focus.

To solve this problem, HTML5 introduces an autofocus attribute on all web form controls. The autofocus attribute does exactly what it says on the tin: it moves the focus to a particular input field. But because it’s just markup instead of a script, the behavior will be consistent across all web sites. Also, browser vendors (or extension authors) can offer users a way to disable the autofocusing behavior.

Checking for autofocus support uses detection technique #2. If your browser supports autofocusing web form controls, theDOM object it creates to represent an <input> element will have an autofocus property (even if you don’t include theautofocus attribute in your HTML). If your browser doesn’t support autofocusing web form controls, the DOM object it creates for an <input> element will not have an autofocus property. You can detect autofocus support with this function:

function supports_input_autofocus() { var i = document.createElement('input'); return 'autofocus' in i; }

Instead of writing this function yourself, you can use Modernizr (1.1 or later) to detect support for autofocused form fields.

↶ check for autofocus support

if (Modernizr.input.autofocus) { // autofocus works! } else { // no autofocus support :( // fall back to a scripted solution }

MICRODATA

alphabetized folders
Your browser does not support the HTML5 microdata API. 😦

Microdata is a standardized way to provide additional semantics in your web pages. For example, you can use microdata to declare that a photograph is available under a specific Creative Commons license. As you’ll see in the distributed extensibility chapter, you can use microdata to mark up an “About Me” page. Browsers, browser extensions, and search engines can convert your HTML5microdata markup into a vCard, a standard format for sharing contact information. You can also define your own microdata vocabularies.

The HTML5 microdata standard includes both HTML markup (primarily for search engines) and a set of DOM functions (primarily for browsers). There’s no harm in including microdata markup in your web pages. It’s nothing more than a few well-placed attributes, and search engines that don’t understand the microdata attributes will just ignore them. But if you need to access or manipulate microdata through the DOM, you’ll need to check whether the browser supports the microdata DOM API.

Checking for HTML5 microdata API support uses detection technique #1. If your browser supports the HTML5 microdata API, there will be a getItems() function on the global document object. If your browser doesn’t support microdata, thegetItems() function will be undefined.

function supports_microdata_api() { return !!document.getItems; }

Modernizr does not yet support checking for the microdata API, so you’ll need to use the function like the one listed above.

FURTHER READING

Specifications and standards:

JavaScript libraries:

  • Modernizr, an HTML5 detection library
  • geo.js, a geolocation API wrapper

Other articles and tutorials: