你的位置: 首页 畅游 HTML 5


HTML5 特性的检测

 

潜入

Y你可能会问: “如果旧的浏览器不支持HTML5, 我该怎么开始使用它呢?” 但是这个问题本身会让人产生误解. HTML5 不是一个大事件; 它是个体特性的集合. 因此你不能检测是否 “支持HTML5”, 因为那没有任何意义. 但是你可以检测是否支持个体的特性, 如 canvas, video, 或者 geolocation.

检测技术

当你的浏览器在渲染一张网页时, 它会构建一个文档对象模型(DOM), 就是一个将HTML元素展示在网页上的对象集合. 每个元素 — 每个 <p>, 每个 <div>, 每个 <span> — 都被不同的对象呈现于DOM中. (当然也有不依赖于特定元素的全局对象, 如 window and document.)

girl peeking out the window

全部的 DOM 对象共享一组共同的属性, 但是一些对象拥有的(属性)比其它对象要多. 在支持HTML5特性的浏览器中, 某些对象拥有的属性是特有的. 快速预览一下DOM你便可以知道哪些特性是被支持的.

有四种基本技术可以检测浏览器是否支持某些特性. 从最简单的到非常复杂的依次是:

  1. 检查某个属性是否存在于全局对象中 (比如 window 或者 navigator).

    例子: 测试对 geolocation 的支持

  2. 创建一个元素, 然后检测这个元素是否存在某个属性.

    例子: 测试对 canvas 的支持

  3. 创建一个元素, 检查这个元素是否存在某个方法, 然后调用这个方法并检查它的返回值.

    例子: 测试支持哪些 video 格式

  4. 创建一个元素, 给某个属性设置一个值, 然后检查该属性是否保存它的值.

    例子: 测试支持哪些 <input> 类型

HTML5 检测库 Modernizr

Modernizr 是一个以MIT协议开源的JavaScript库,用于检测HTML5 & CSS3众多特性的支持. 至写本文之时, Modernizr的最新版本是 1.5. 你应该使用最新版本. 在使用时你还应该在页面顶端采用如下的<script>元素.

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

 ↜ 放在网页的 <head> 部分

Modernizr是自动运行的. 它不需要调用任何 modernizr_init() 方法. 当它运行的时候, 它会创建一个名为Modernizr的全局对象, 该全局对象包含一组可检测特性的布尔属性. 例如, 如果你的浏览器支持 canvas API, Modernizr.canvas Modernizr.canvas属性值就会为真(true). 如果你的浏览器不支持 the canvas API, Modernizr.canvas 属性就为假(false).

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

Canvas

man fishing in a canoe

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.

Canvas Text

baseball player at bat

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 :(
}

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

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 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

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

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. 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:

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

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 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).

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

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”).

Offline Web Applications

cabin in the woods

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

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

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 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.

Input 类型

manual typewriter

你对网页表单已经相当熟悉了, 对吧? 创建一个 <form>, 再添加几个 <input type="text"> 元素或者一个 <input type="password">, 然后再以 <input type="submit"> 按钮结束, 这样一个表单就做好啦!

如果真是这样, 那么你对表单只是一知半解. HTML5 对表单的一系列input类型做了详细的定义, 这些定义在你的表单中都可以使用得到.

  1. <input type="search"> 用于搜索框
  2. <input type="number"> 用于(数字)微调框
  3. <input type="range"> 用于滑块
  4. <input type="color"> 用于拾色器
  5. <input type="tel"> 用于电话号码
  6. <input type="url"> 用于网页地址
  7. <input type="email"> 用于电子邮件地址
  8. <input type="date"> 用于日历日期选择器
  9. <input type="month"> 用于月份
  10. <input type="week"> 用于星期
  11. <input type="time"> 用于时间
  12. <input type="datetime"> 用于精确的日期和时间
  13. <input type="datetime-local"> 用于本地日期和时间

检测HTML5 input类型使用 第四项检测技术, 这里介绍一下它的创建过程. 首先, 在内存中创建一个虚拟的 <input> 元素. 所有的<input>元素的默认input类型为"text". 稍后你会发现这点是非常重要的.

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

接着, 将该<input>元素的type属性设置成你想要检测的输入类型.

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

如果你的浏览器支持某个输入类型, type特性将保留你设置的值. 如果你的浏览器不支持某个输入类型, 它将忽略你设置的值, 而 type 属性仍保持为 "text".

  return i.type !== "text";

有了Modernizr,你可以使用它来检测所有HTML5最新定义过的输入类型的支持, 这样你就不必费神自己去写这十三个单独的函数. Modernizr 可以对单个的 <input> 元素进行重复使用, 从而达到高效地检测这十三个输入类型的支持的目的. 然后它构建一个名为 Modernizr.inputtypes 的哈希表, 该哈希表共包含了13个键( HTML5 的13个type 属性) 和13个布尔值 (true 表示支持该类型, false 表示不支持)组成的键值对.

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 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
}

Form Autofocus

angry guy with arms up

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

alphabetized folders

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.

Further Reading

Specifications and standards:

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.

Did You Know?

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–MMX Mark Pilgrim