You are here: Home ‣ Dive Into HTML5 ‣
❧
ou 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 “HTML5 support,” because that doesn’t make any sense. But you can detect support for individual features, like canvas, video, or geolocation.
❧
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.)
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:
Check if a certain property exists on a global object (such as window
or navigator
).
Example: testing for geolocation support
Create an element, then check if a certain property exists on that element.
Example: testing for canvas support
Create an element, check if a certain method exists on that element, then call the method and check the value it returns.
Create an element, set a property to a certain value, then check if the property has retained its value.
❧
Modernizr is an open source, MIT-licensed JavaScript library that detects support for many HTML5 & CSS3 features. 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 called Modernizr
, that contains a set of Boolean properties for each feature it can detect. For example, if your browser supports the canvas API, the Modernizr.canvas
property will be true
. If your browser does not support the canvas API, the Modernizr.canvas
property will be false
.
if (Modernizr.canvas) {
// let's draw some shapes!
} else {
// no native canvas support available :(
}
❧
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, 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() {
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 shapes, paths, gradients & 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.
❧
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 the supports_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 :(
}
❧
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®.
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.
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 HTML5 video 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 supports HTML5 video, the DOM object it creates to represent a <video>
element will have a canPlayType()
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 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.
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 supports HTML5 video, the DOM object it creates to represent a <video>
element will have a canPlayType()
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 the canPlayType()
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.)
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
}
}
❧
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.
☞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 the HTML5 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 a localStorage
property on the global window
object. If your browser doesn’t support HTML5 storage, the localStorage
property 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).
☞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 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 Worker
property 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”).
❧
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 an applicationCache
property on the global window
object. If your browser doesn’t support offline web applications, the applicationCache
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 DOM object is called window.applicationCache
(mixed case).
❧
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.
☞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 the HTML5 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 a geolocation
property on the global navigator
object. If your browser doesn’t support the geolocation API, the geolocation
property 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 BlackBerry, Nokia, Palm, and OMTP BONDI.
The chapter on geolocation will go into excruciating detail about how to use all of these different APIs.
❧
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.
<input type="search">
for search boxes
<input type="number">
for spinboxes
<input type="range">
for sliders
<input type="color">
for color pickers
<input type="tel">
for telephone numbers
<input type="url">
for web addresses
<input type="email">
for email addresses
<input type="date">
for calendar date pickers
<input type="month">
for months
<input type="week">
for weeks
<input type="time">
for timestamps
<input type="datetime">
for precise, absolute date+time stamps
<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
}
❧
Besides new input types, HTML5 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, the DOM object it creates to represent an <input>
element will have a placeholder
property (even if you don’t include a placeholder
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
}
❧
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, the DOM object it creates to represent an <input>
element will have an autofocus
property (even if you don’t include the autofocus
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 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 HTML5 microdata 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, the getItems()
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.
❧
The HTML5 history API is a standardized way to manipulate the browser history via script. Part of this API — navigating the history — has been available in previous versions of HTML. The new part in HTML5 is a way to add entries to the browser history, and respond when those entries are removed from the stack by the user pressing the browser’s back button. This means that the URL can continue to do its job as a unique identifier for the current resource, even in script-heavy applications that don’t ever perform a full page refresh.
Checking for HTML5 history API support uses detection technique #1. If your browser supports the HTML5 history API, there will be a pushState()
function on the global history
object. If your browser doesn’t support the history API, the pushState()
function will be undefined.
function supports_history_api() {
return !!(window.history && history.pushState);
}
Instead of writing this function yourself, you can use Modernizr (1.6 or later) to detect support for the HTML5 history API.
↶ check for history API support
if (Modernizr.history) {
// history management works!
} else {
// no history support :(
// fall back to a scripted solution like History.js
}
❧
Specifications and standards:
<canvas>
element
<video>
element
<input>
types
<input placeholder>
attribute
<input autofocus>
attribute
JavaScript libraries:
Other articles and tutorials:
❧
This has been “Detecting HTML5 Features.” The full table of contents has more if you’d like to keep reading.
In association with Google Press, O’Reilly is distributing this book in a variety of formats, including paper, ePub, Mobi, and DRM-free PDF. The paid edition is called “HTML5: Up & Running,” and it is available now. This chapter is included in the paid edition.
If you liked this chapter and want to show your appreciation, you can buy “HTML5: Up & Running” with this affiliate link or buy an electronic edition directly from O’Reilly. You’ll get a book, and I’ll get a buck. I do not currently accept direct donations.
Copyright MMIX–MMXI Mark Pilgrim