HTML5: What You Should Be Using Right Now

Continuing our examination of HTML5, this time we’ll take a slightly deeper look at the state of HTML5 support in browsers. We’ll step through several major features, examine the technical hurdles in place, identify the level of browser support and finally provide some recommendations on whether or not to pull the trigger with that shiny new feature.

New Semantic Elements

HTML5 has added many new semantic elements. These both codify existing, common patterns and offer new, meaningful ways mark up your content. So, for example, going forward, instead of using <div id="header"> we will now just use <header>. Some other examples (with definitions culled from the specification) include:

section
The section element represents a generic document or application section. A section, in this context, is a thematic grouping of content, typically with a heading.

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site’s home page could be split into sections for an introduction, news items, contact information.

footer
The footer element represents a footer for its nearest ancestor sectioning content or sectioning root element. A footer typically contains information about its section such as who wrote it, links to related documents, copyright data, and the like.
nav
The nav element represents a section of a page that links to other pages or to parts within the page: a section with navigation links.
article
The article element represents a component of a page that consists of a self-contained composition in a document, page, application, or site and that is intended to be independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

That’s far from a complete list, but it should serve to give you the flavor of what’s available.

Support

This is a curious case. If, by “support” we mean “doesn’t break anything” then the support here is broad. Using the HTML5 Shiv code snippet or the full blown Modernizr library every browser that matters supports the HTML5 elements. If you’re expecting user agents to do something interesting with your new elements, then the support level is much lower.

The Verdict

Do it. This very site is built using the new semantic elements and it’s the fourth such site I’ve built in the past year. I’m happy to report- I’m still standing. While there’s a slightly higher degree of difficulty and there’s less certainty around HTML5 best practices than exists for earlier flavors of HTML; the hands-on experience with the new elements is enough reason to start using them as soon as possible. All the tutorials in the world can’t stand up to using the new elements against your site and solving your own problems with them.

How-to

Pretty easy, really. To allow the styling of the new elements in Internet Explorer (other browsers automatically allow unknown elements to be styled), either include the HTML5 Shiv

<!DOCTYPE html>
  <htmlclass="no-js">
  <head
  <meta charset="UTF-8">
  <!--[if lt IE 9]>
  <script>  var elem;  var elems = 'abbr article aside audio canvas datalist details eventsource figure footer header hgroup mark menu meter nav output progress section time video'.split(' ');  var i = elems.length+1;  while ( --i ) {  	elem = document.createElement( elems[i] );  }  elem = null;
  </script>
  <![endif]>
  <title>HTML Shiv</title>  

or Modernizr:

<!DOCTYPE html>
<html class="no-js">
<head>
  	<meta charset=utf-8" />
  	<title>Modernizr</title>
  	     <script src="/i/js/modernizr.custom.2.6.1-01.js"></script>  

and you’re ready to start in with the new HTML5 elements. what you do with those new elements is beyond the scope of this article, but there are plenty of resources out there talking about how to use the new HTML5 elements, to help you get started.

Video

This has become so pervasive a topic that for some people “HTML5” is shorthand for the new <video> element. With Apple blocking Adobe’s otherwise ubiquitous Flash player from iOS, much attention has been focused on the HTML5 alternative. This is good, because the more people talking about HTML5, the better chance we’ll have of all the browser manufacturers implementing the new features.

It’s also slightly problematic because of all the new HTML5 features the new video element might be the most messed up at the present time.

Support

Technically, “video” is supported by the latest versions of Chrome, Safari, Firefox and Opera, with support coming in Internet Explorer 9.

That’s the happy check-box view.

The reality is slightly more confusing (and less happy) as simply supporting the video element and related APIs is only half the story. What codecs and containers each browser supports is as important as element/api support and unfortunately for all of us, battle lines have been drawn. Without getting into too much detail, there are basically two camps*- browsers that support open source solutions (currently Theora and VP8) and those that support h.264, a patent encumbered codec. In the open source camp we have Opera and Firefox. In the patent encumbered corner we have Apple and Microsoft’s Internet Explorer 9. All of this means that there are no easy answers on how to move forward with the new video element, at least if the goal is to provide HTML5 video to the largest possible audience.

Things get a little easier if the only goal is to bring video to the iOS and other mobile devices. It’s still more complicated than the current Flash based solution, but it’s doable- at least with the right resources.

The Verdict

If you’re dying to get your video content onto the iPad and other mobile devices and you have the resources, then, yes. Be warned, however, it brings with it added complexity, so factor that into your decision-making.

How-to

Unfortunately, because of the codec fragmentation the only worthwhile solution right now** is to ignore the open source solutions and encode your video as h.264 and package it in an MP4 container. That codec/container combination can be read by the video element in Safari and Chrome on the desktop as well as on Android phones and iOS. Most importantly, it can also be read by Flash. Which means, with a bit of smart coding on the HTML side, you can ensure that the widest possible range of devices will be able to consume your video.

What does that smart coding look like?

It looks like Video for Everybody.

The basic pattern looks like this:


<!-- Start with HTML5 playback-->  	
<video width="640" height="360" controls preload="none">  	
	<source src="example.MP4" type="video/mp4" /><!-- WebKit video    -->  	
	<!-- and then fallback to Flash: -->  	
	<object width="640" height="384" type="application/x-shockwave-flash" data="video-player.SWF">  	
		<!-- FLASH STUFF -->
		<!--video-player.swf can play example.mp4 -->   	
	</object>  	
</video>

This is a reasonable solution because you only have to encode and store one mp4 version of the video and it will cover pretty much any browser/OS combination that matters.

Additionally, outfits like BrightCove are working similar techniques into their platform work. Worth keeping in mind if you’re shopping for video solutions.

*Technically we have a third camp, as Google, with their Chrome browser, actually supports both.
**Hopefully everyone will come together under the WebM banner, since it solves both the patent and quality arguments of the two warring camps, but that’s for the future to decide.

Geolocation

Geolocation, a method of informing a website or web application of a user’s geographical location, isn’t “proper” HTML5, but it is of interest these days and is generally included as part of the informal specification, so I’m including it here.

Support

The new navigator.geolocation object is supported by Firefox 3.5+, Chrome 5.0+, Safari 5.0+, iPhone 3.0+ and Android 2.0+. Beyond that, using something like Google Gears, or even just the user’s IP address, it’s possible to get some location data using other sources. Here’s a quick demo using the YQL Geo Library. It should do something in pretty much any browser.

The Verdict

If you don’t need absolute precision for all users or then by all means, work some secondary geolocation features into your site or web application. You can do a reasonable job in a wide range of browsers. If you’re trying to get high quality location data then your options are a little more limited in the browser.

How-to

Using a library like geo.js or the previously mentioned YQL Geo Library smooths out the rough patches between the geolocation api itself and the various fallback methods. For a quick illustration of how easy it is to get basic data, here’s the entire script used in the above demo:


document.getElementById("geolocate").onclick= function() {
      yqlgeo.get('visitor',function(o){
			var result = document.getElementById("result");
			result.innerHTML += " " + o.place.name + "," + o.place.country.content +  " (" + o.place.centroid.latitude + "," + o.place.centroid.longitude + ")";
			result.style.display="block";
		}
	)
}

Not much to it, but using that you’ve got a friendly place name (which is provided by a yql service, not the geolocation api itself) and lat/long (the heart of the actual geolocation api). From there you’ve ready to spin a web of location-based wonder and amazement.

Looking to the future, using the actual underlying geolocation api isn’t much more verbose with the navigator.geolocation.getCurrentPosition providing a straightforward interface to the browser’s location data.

Web Storage

Web Storage is a method of storing data, in the form of name/value pairs, locally on a user’s machine. File this one under: not flashy, but super useful.

Support

Stunningly, the latest version of every major browser supports localStorage. You get 5MB of persistent storage across the board. For IE7 and IE6, if you really had to figure out a local storage solution, you could potentially leverage userData or Gears, both of which offer similar functionality.

The Verdict

With such broad support, it makes sense to start enhancing pages with localStorage. Saving trips to the server is always good, so storing more (non-sensitive*) data on the client side is going to be a positive for your users.

How-to

At the most basic level, there are three things you need to know about, setting items, getting items and the storage event.

//use modernizr to test for support
if (Modernizr.localstorage) {
    // window.localStorage is a go!
    function setGet(){
        //set some data. It's stored as a String, btw. 
        localStorage.setItem("dharma.station.swan.status", "destroyed",);  
        //get some data
        var swanStatus = localStorage.getItem("dharma.station.swan.status");
    }
    //we can also listen for storage events
    function omgStorage(){
        alert("someone stored something. Just though you should know.");
    }
window.addEventListener("storage", omgStorage, false); 
} 

PersistJS

PersistJS is an excellent, cross-browser interface to the fll spectrum of localStorage and related solutions. Providing a single interface to the W3C version, Internet Explorer’s, Gear’s and even Flash’s implementation, Persist is a solid solution for the current fragmented local storage landscape.

Here’s what a simple example of Persist looks like in action:


var store = new Persist.Store("MyData");store.set("MyName", "Rob Larsen")
store.get("MyData", function(ok,data){
	if(ok){
	    	console.log(data);
	   }
   })
   

*data is saved unencrypted on disk

Canvas

To quote the spec, Canvas is “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly.” It’s one of the most exciting of the new HTML5 features because it promises the ability to do really advanced graphics, games and visualizations right in the browser- without the aid of a plugin. Staying within the web standards stack we can now start to do some of the things we relied on Flash for up until now.

Support

The latest version of every browser but Internet Explorer supports Canvas natively. Thankfully, support for IE can be provided by the Explorercanvas library, a clever bit of coding that transforms Canvas methods into VML. The downside to that is, of course, speed. Performance for more complicated Canvas scripting is very slow on IE. This is especially true for animations and interactive elements. In addition there are several canvas features that simply don’t translate. Still, it’s a viable solution.

The Verdict

If you’re willing to sacrifice a little bit of speed in IE and aren’t pushing the boundaries of what Canvas is capable of, it’s pretty safe to start using Canvas right now. Explorercanvas works pretty well, and in browsers that support it natively, the experience can be great.

There are also concerns about accessibility, which is definitely something to keep in mind.

How-to

A proper how-to for the canvas element is beyond the scope of this article. In place of that here’s an extremely simple demo and some code that will hopefully illustrate basic concepts.

Here’s the demo. It converts a data table into a bar chart using some canvas methods.

Wow, that was fun.

Let’s look at the code.

The HTML is nothing special. The Canvas element just sits there until JavaScript brings it to life.


<table id="data-table">
    <tr>
        <td>15</td>
        <td>25</td>
        <td>10</td>
        <td>25</td>
        <td>50</td>
    </tr>
</table>
<button id="canvas-controller">Chart It!</button>
<canvas id="canvas-sample" width="350" height="200">
</canvas>

Here’s the JavaScript. Comments inline.


document.getElementById("canvas-controller").addEventListener("click", writeCanvas, false);

function writeCanvas(e){
//we need a reference to the canvas. Typical DOM stuff
    var canvas = document.getElementById("canvas-sample");
//Then we get the "context." It's the reference 
//to the drawing surface itself. 
var context = canvas.getContext("2d"); 
//get the data cells
    var tds = document.getElementById("data-table").getElementsByTagName("td");
//set up a list of colors
    var colors = ["#3366FF",
        "#6633FF",
        "#003DF5",
        "#002EB8",
        "#66FF33"
    ];
//Let's draw some grid lines
    for (var y = 0; y < canvas.offsetHeight; y += 10) {
//moveTo and lineTo are pretty clearly named functions.
//move the "point" to a new place
	    context.moveTo(0, y);
//and plot a line
    	context.lineTo(canvas.offsetWidth, y);
    }
//what's not clear is that running the above commands doesn't 
//actually draw anything. These next two commands do.
//set a style for line "stroke"
    context.strokeStyle = "#ccc";
//and then call the function that makes the lines happen
    context.stroke();
//set a bunch of variables
    var basewidth, spacing, width, height, posx, posy;
//loop through
var i = tds.length;
	while (i--) {
//calculate a uniform "base" width for the bars 
   	basewidth = canvas.offsetWidth/tds.length;
//set up some spacing
    	spacing = basewidth/4;
//calculate the actual width of the bars
    	width = basewidth - spacing;
//set up a height. This isn't actually to any scale. 
//It just looked good :)
    	height = parseInt(tds[i].innerHTML)*3;
//calculate the x position with some spacing between the bars
    	posx = (i * basewidth) + spacing/2;
//pin the bars to the bottom of the canvas
    	posy= canvas.offsetHeight-height;
//set the color
    	context.fillStyle = colors[i];
//and then fill it. 
//The fillRect takes (x,y,width,height) as arguments
    	context.fillRect(posx, posy, width , height );
    }
//stop the clicks.
    e.preventDefault();
}


And that’s that.

Hopefully you’ve come away with a better understanding of the current support levels for HTML5. All in all, it’s really not that bad. The landscape is manageable for many of the newest technologies and if we can light a fire under Microsoft to release IE9 it’ll only get better.

So basically, pick your spots, understand the risks, and dive right in.


This post originally appeared on the Isobar North America blog

4 thoughts on “HTML5: What You Should Be Using Right Now

  1. Hi Rob,

    Nice presentation on all these HTML5 topics. Thanks. I’ve been surfing for info and came by some on my own, but nothing as concise and useful as your list of scripts and techniques. I wonder if you have any preferences on HTML5 frameworks for mobile? Like JQTouch, Sencha or the like. Seems to be many out there, but looking to narrow the field to one or two of the best. Any incite would be welcome.

  2. Thanks. Glad to pass on what I’ve learned so far.

    As for mobile, the two you’ve mentioned are the two I’d speak to, normally. We’ve used JQTouch. It’s solid. We were able to ramp up very quickly with some pretty cool effects. That was for some short term demo work. If I were starting a new project, with larger scope, I’d definitely look at Sencha first. It looks very solid.

  3. i need to make a business website for a company. i’m using dreamweaver but it is kind of difficult to understand how to do frames and make frame sheets (i think i said that right). anyone know of an easier and the best webdesign software that i could use?.

  4. HTML5 made a big rush, as soon as it came, i started using HTML5 doctype and now i have designed more than 50 sites completely based on HTML5 and CSS3… Overall it rockz….

Leave a Reply

Your email address will not be published. Required fields are marked *