Pergi ke kandungan

Menyelami HTML5/Mengesan Ciri-ciri HTML5: Amat Mudah, Wahai Watson

Daripada Wikibuku
Menyelami HTML5
Sejarah (Berat Sebelah) HTML5 Mengesan Ciri-ciri HTML5: Amat Mudah, Wahai Watson Apa Maksudnya Semua Ini?

No 3. Mengesan Ciri-ciri HTML5

[sunting]

Menyelam Masuk

[sunting]

Anda mungkin bertanya: "Bagaimana dapat saya mengguna HTML5 jika ia tidak disokong pelayar-pelayar lama?" Akan tetapi soalan itu sendiri mengelirukan. HTML5 bukan satu benda yang besar; ia himpunan ciri-ciri individu. Jadi anda tidak dapat mengesan "sokongan HTML5", kerana itu tidak ada makna. Akan tetapi, anda dapat mengesan ciri-ciri individu seperti kanvas, video atau geolocation.

Teknik-teknik Mengesan

[sunting]

Apabila pelayar anda memaparkan sebuah halaman sesawang, ia membina Model Objek Dokumen (Document Object Model (DOM)), himpunan objek-objek yang mewakili kesemua unsur HTML yang terkandung dalam dokumen. Setiap unsur — setiap <p>, setiap <div>, setiap <span> — diwakili dalam DOM oleh objek berlainan. (Terdapat juga objek global, seperti tetingkap (window) dan dokumen (document) yang tidak terikat dengan unsur spesifik.)

Semua objek DOM berkongsi satu set sifat yang sama, akan tetapi sebahagian objek memiliki lebih banyak sifat berbanding yang lain. Dengan pelayar yang menyokong ciri HTML5, objek-objek tertentu mempunyai sifat yang unik. Intaian ringkas DOM akan dapat memberi tahu kita ciri yang mana disokong.

Terdapat empat teknik asas yang digunakan untuk mengesan sama ada sesuatu pelayar itu menyokong sesuatu ciri. Daripada paling mudah hingga ke paling rumit:

  1. Periksa sama ada sesuatu sifat itu wujud pada objek global (seperti tetingkap atau pemandu arah).
    Contoh: menguji sokongan geolocation
  2. Wujudkan unsur, kemudian periksa sama ada sesuatu sifat itu wujud pada unsur tersebut.
    Contoh: menguji sokongan kanvas
  3. Wujudkan unsur, periksa sama ada kaedah (method) tertentu wujud, kemudian panggil kaedah tersebut dan periksa nilai yang dipulanginya.
    Contoh: menguji sokongan format video
  4. Wujudkan sebuah unsur, tetapkan sifat kepada nilai tertentu, kemudian periksa sama ada ia mengekalkan nilai tersebut.
    Contoh: menguji sokongan <input>.

Modernizr, Perpustakaan Pengesan HTML5

[sunting]

Modernizr (P: ejaan betul) ialah sebuah perpustakaan JavaScript sumber terbuka di bawah lesen MIT yang mengesan sokongan bagi banyak ciri HTML5 dan CSS3. Anda seharusnya menggunakan versi mutakhir. Untuk menggunanya, masukkan unsur <script> di bahagian atas dokumen anda.


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

Ia dimuatkan ke dalam <head>.

Modernizr berjalan secara automatik. Tiada fungsi modernizr_init() yang perlu dipanggil. Apabila ia dijalankan, ia mewujudkan sebuah objek global yang dipanggil "Modernizr", yang mengandungi satu set sifat Boolean bagi setiap ciri yang dapat dikesani. Misalnya, jika pelayar anda menyokong API kanvas (canvas API), sifat Modernizr.canvas menjadi benar. Jika pelayar anda tidak menyokong API kanvas, sifat Modernizr.canvas menjadi palsu.

if (Modernizr.canvas) {
  // mari kita lukis beberapa bentuk!
} else {
  // tiada sokongan natif buat kanvas :(
}

Kanvas

[sunting]

HTML5 memberi definisi <canvas> sebagai "kanvas peta bit bebas peleraian yang dapat digunakan bagi memaparkan graf, grafik permainan, atau imej-imej visual lain secara layang." Kanvas ialah sebuah segi empat tepat di mana anda dapat menggunakan JavaScript untuk melukis apa saja yang anda mahu. HTML5 mentakrifkan seset fungsi ("API kanvas") bagi melukis bentuk, laluan, curam, dan mengenakan transformasi.

Memeriksa API kanvas menggunakan teknik #2. Jika pelayar anda menyokong API kanvas, objek DOM yang direkanya untuk mewakili unsur <canvas akan mempunyai kaedah getContext() . Jika pelayar anda tidak menyokong API kanvas, objek DOM yang direka buat unsur <canvas> akan memiliki hanya set sifat guna sama, tetapi tiada yang spesifik untuk kanvas.

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

Fungsi ini bermula dengan membuat unsur <canvas> olok-olok. Akan tetapi unsur ini tidak dikepilkan pada laman anda, jadi tiada siapa yang akan melihatnya. Ia hanya akan berada dalam ingatan, tidak ke mana dan tidak berbuat apa-apa, seperti sebuah perahu yang terapung-apung di dalam sungai.

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

Sebaik sahaja anda membuat unsur <canvas> olok-olok, anda periksa kehadiran kaedah getContext(). Kaedah ini akan hanya wujud jika pelayar anda menyokong API kanvas.

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

Akhir sekali, anda guna helah negatif ganda untuk memaksa hasil kepada nilai Boolean (benar atau palsu).

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

Fungsi ini akan mengesan sokongan buat kebanyakan API kanvas, termasuk bentuk, laluan, curam dan pola. Ia tidak akan mengesan perpustakaan pihak ketiga, explorercanvas, yang melaksanakan API kanvas dalam Internet Explorer Microsoft.

Daripada anda menulis fungsi ini sendiri anda boleh menggunakan Modernizr untuk mengesan sokongan buat API kanvas.

Menentukan sokongan buat kanvas:

if (Modernizr.canvas) {
  // mari kita lukis beberapa bentuk!
} else {
  // tiada sokongan natif buat kanvas :(
}

Terdapat ujian berlainan bagi API teks kanvas, yang akan saya tunjukkan di bawah.

Teks Kanvas

[sunting]

Mahupun pelayar anda menyokong API kanvas, ia mungkin tidak menyokong API teks kanvas. API kanvas berkembang dengan peredaran masa, dan fungsi-fungsi teks ditambah pada waktu yang agak lambat. Ada beberapa pelayar diedarkan dengan sokongan buat kanvas sebelum API teks dapat disempurnakan.

Memeriksa kehadiran API teks kanvas menggunakan teknik #2. Jika pelayar anda menyokong API kanvas, objek DOM yang dibuatnya untuk mewakili unsur <canvas> akan mengandungi kaedah getContext() . Jika pelayar anda tidak menyokong API kanvas, objek DOM yang dibuatnya untuk unsur ,canvas hanya akan memiliki set sifat guna sama tetapi tiada yang khusus untuk kanvas.

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

Fungsi ini bermula dengan memeriksa sokongan kanvas, menggunakan fungsi supports_canvas() yang anda lihat dalam bahagian sebelum ini. Sekiranya pelayar anda tidak menyokong API kanvas, ia tentu sekali tidak menyokong API teks kanvas!

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

[sunting]

HTML5 mendefinisi unsur baharu digelar <video> bagi pembenaman video dalam halaman sesawang. Pembenaman video dahulu kala tidak dapat dilakukan tanpa penggunaan plugin (palam) pihak ketiga seperti Apple QuickTime® atau Adobe Flash®.

Unsur <video> direka agar dapat digunakan tanpa mengguna skrip pengesan. Anda dapat menetapkan pelbagai format video dan pelayar yang menyokong video HTML5 akan memilih satu berlandaskan format video yang disokong (lihat A gentle introduction to video encoding part 1: container formats dan part 2: lossy video codecs untuk mempelajari jenis-jenis format video).

Pelayar-pelyar yang tidak menyokong video HTML5 akan mengabaikan <video>, tetapi anda boleh memfaatkan hakikat ini dan memberitahu pelayar untuk memainkan video dengan mengguna plugin pihak ketiga. Kroc Camen mencipta satu penyelesaian bergelar Video for Everybody! (Video untuk Semua) yang menggunakan video HTML5 di mana boleh, akan tetapi akan mengguna QuickTime atau Flash dengan pelayar-pelayar laman. Penyelesaian ini tidak mengguna JavaScript, dan bekerja dalam hampir semua pelayar, termasuk pelayar mudah alih.

Jika anda mahu mengguna video lebih lanjut daripada hanya untuk memainkannya, anda perlu mengguna JavaScript. Memeriksa kehadiran sokongan video menggunakan teknik#2. Jika pelayar anda menyokong video HTML5, objek DOM yang diwujudkannya bagi mewakili unsur <video> akan memiliki kaedah canPlayType() (harfiah, bolehMainJenis() ). Jika pelayar anda tidak menyokong video HTML5, objek DOM yang dibuat untuk unsur <video> akan hanya memiliki set sifat-sifat guna sama yang terdapat pada semua unsur. Anda dapat mengesan sokongan video dengan fungsi ini:

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

Anda boleh menggunakan Modernizr untuk megesan sokongan video HTML5 dengan tanpa perlu menulis kod ini sendiri.

Menegsan sokongan buat video HTML5:

if (Modernizr.video) {
  // mari main video!
} else {
  // tiada sokongan natif buat video  :(
  // cuba kesan QuickTime atau Flash 
}

Dalam bab tentang video, saya akan menerangkan penyelesaian lain yang menggunakan teknik-teknik mengesan ini untuk mengalih unsur-unsur <video> kepada pemain-pemain video berasaskan Flash, buat pelayar-pelayar yang tidak menyokong video HTML5.

Terdapat ujian berasingan bagi mengesan format video apa yang dapat dimainkan pelayar anda, yang akan saya tunjuk berikutnya.

Format-format Video

[sunting]

Format-format video mirip bahasa tertulis. Surat khabar Inggeris mungkin menyampaikan maklumat yang sama dengan akhbar Sepanyol, tetapi jika anda hanya boleh membaca bahasa Inggeris, hanya satu yang berguna buat anda! Untuk memainkan sesuatu video, pelayar anda perlu memahami "bahasa" penulisan video tersebut.

"Bahasa" sesuatu video itu digelar "codec" — inilah algoritma yang digunakan bagi mengekod video ke dalam strim bit. Terdapat berdozen codec yang digunakan merata dunia. Yang mana satu harus anda guna? Malangnya, hakikat video HTML5 adalah pelayar tidak dapat bersetuju tentang codec tunggal. Walau bagaimanapun, peleyar-pelayar ini nampaknya telah mengecilkan pilihan kepada satu atau dua. Satu codec memerlukan wang (kerana lesen paten), tetapi ia bekerja dengan Safari dan iPhone (yang ini juga bekerja dengan Flash sekiranya anda mengguna penyelesaian seperti Video for Everybody!). Codec yang lagi satu percuma dan bekerja dengan pelayar sumber terbuka seperti Chromium dan Mozilla Firefox.

Pengesanan sokongan format video menggunakan teknik mengesan #3. Jika pelayar anda mengesan video HTML5, objek DOM yang diciptanya bagi mewakili unsur <video> akan memiliki kaedah canPlayType() . Kaedah ini akan memberitahu anda sama ada pelayar menyokong format video tertentu.

Fungsi ini mengesan format yang terikat paten yang disokong Mac dan iPhone.

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"');
}

Fungsi ini bermula dengan mengesan sokongan video HTML, dengan mengguna fungsi supports_video() yang baharu anda lihat. Jika pelayar anda tidak menyokong video HTML5, ia tidak akan menyokong apa jua format video!

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

Kemudian fungsi ini mewujudkan unsur <video> semu (tetapi tidak melampirkannya pada halaman, jadi ia tidak kelihatan) dan memanggil kaedah canPlayType(). Kaedah ini pasti hadir kerana fungsi supports_video() baharu sahaja memeriksa kehadirannya.

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

"Format video" sebenarnya gabungan beberapa perkara. Dalam erti kata teknikal, anda menanya pelayar sama ada ia dapat memainkan video H.264 Baseline dan audio AAC LC dalam kontena atau bekas MPEG-4 container (Saya akan menerangkan apa maksud semua ini dalam bab Video. )

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

Fungsi canPlayType() ( bolehMainJenis () ) tidak memulangkan nilai benar atau palsu. Memandang format-format video itu kompleks, fungsi ini memulangkan rentetan:

  • "probably" (barangkali) jika pelayar agak yakin ia dapat memainkan format
  • "maybe" (mungkin) jika pelayar berasa ia mungkin dapat memainkan format
  • "" (rentetan kosong) jika pelayar pasti ia tidak memainkan format

Fungsi kedua ini mencari format video terbuka yang disokong Mozilla Firefox dan pelayar sumber terbuka lain. Prosesnya sama; perbezaan hanya dengan rentetan yang anda beri kepada fungsi canPlayType(). Dari segi teknikal, anda menanya pelayar sama ada ia dapat memainkan video Theora dan audio Vorbis dalam kontena Ogg.

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 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 :(
 // try a fallback 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 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 :(
 // try a fallback 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 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 :(
 // try a fallback 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 not be present inside of navigator. Here’s how to check for geolocation support:

function supports_geolocation() {

 return 'geolocation' in navigator;

}

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 :(
 // try geoPosition.js or another third-party solution

}

If your browser does not support the geolocation API natively, there is still hope. GeoPosition.js is a JavaScript library that aims to provide Geolocation support in older browsers like Blackberry, Palm OS, and Microsoft Internet Explorer 6, 7, and 8. It’s not quite 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 Types

manual typewriter

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

}

Placeholder Text

linotype model 25 - one of the machines that helped create a demand for lorem ipsum placeholder text in exhibiting fonts

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.

History API

demon reading book

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

}

Further Reading

Specifications and standards:

   the <canvas> element
   the <video> element
   <input> types
   the <input placeholder> attribute
   the <input autofocus> attribute
   HTML5 storage
   Web Workers
   Offline web applications
   Geolocation API
   Session history and navigation 

JavaScript libraries:

   Modernizr, an HTML5 detection library
   geo.js, a geolocation API wrapper
   HTML5 Cross-browser Polyfills 

Other articles and tutorials:

   Video for Everybody!
   A gentle introduction to video encoding
   Video type parameters
   The All-In-One Almost-Alphabetical Guide to Detecting Everything
   Internet Explorer 9 Guide for Developers 

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