Bruce Lawson’s personal site

Archive for the 'HTML5' Category

The best of <time>s

Avid HTML5 watchers will know that the <time> element was dropped from HTML, then re-instated, with more New! Improved! semantics.

As before, you can put anything you like between the opening and closing tags – that’s the human-readable bit. The machine-readable bit is contained within a datetime attribute. Dates are expressed YYYY-MM-DD.

Previously, you could only mark up precise dates. So, 13 November 1905 could be expressed in HTML <time datetime="1905-11-13"> but November 1905 couldn’t be. This is a problem for historians where sometimes the precise date isn’t known.

Now, “fuzzy dates” are possible:

  • <time datetime="1905"> means the year 1905
  • <time datetime="1905-11"> means November 1905
  • <time datetime="11-13"> means 13 November (any year)
  • <time datetime="1905-W21"> means week 21 of 1905

As before, times are expressed using the 24 hour clock. Now, you can separate the date and time with a space rather than a “T” (but you don’t have to). So both of these are valid:

  • <time datetime="1905-11-13T09:00">
  • <time datetime="1905-11-13 09:00">

You can localise times, as before. Appending “Z” to the timezone indicates UTC (a way of saying “GMT” without it being comprehensible to normal people). Otherwise, use an offset:

  • <datetime="09:00Z"> is 9am, UTC.
  • <datetime="09:00-05"> is 9am in the timezone 5 hours behind UTC.
  • <datetime="09:00+05:45"> is 9am in Nepal, which is UTC + 5 hours and 45 minutes.

Durations

In New! Improved! HTML5 <time>, you can represent durations, with the prefix “P” for “period”. This uses “W” (or “w”) for weeks, “D” for days, “H” for hours, “M” for minutes and “XQ” for seconds. Just kidding – that’s “S”.

You can separate them with spaces (but you don’t have to). So <time datetime="P4W3D5H"> is a duration of 4 weeks, 3 days and 5 hours, as is <time datetime="P4W 3D 5H">. A duration of 3 hours, 2 minutes and 23.005 seconds is <time datetime="P3H2M23.005S"> or <time datetime="P3H 2M 23.005S">.

This can be boiled down by a machine to a precise number of seconds. Because of this, you can’t specify a duration in terms of months, because a month isn’t a precise number of seconds; a month can last from 28 to 31 days. Similarly, a year isn’t a precise number of seconds; it’s 12 months and February sometimes has an extra day.

You still can’t represent dates before the Christian era, as years can’t be negative.

pubdate

The pubdate attribute (a boolean that indicates that this particular date is the publication date of the parent <article> (or, if there is none, the whole document) is currently missing from the W3C version of the spec, but is still current in the WHATWG version. Its status is unclear to me (but I’m still using it).

Beware Tim Berners-Lee’s elite squad of standards-avenging attack ninjas

It’s been whispered about for some time, but only now can the truth be revealed. The Large Hadron Collider at CERN was built in order to produce enough Higgs Bosons to turn ordinary ninjas into an elite squad of standards-avenging attack ninjas under the sole command of Sir Tim Berners-Lee, previously from CERN (co-incidence? I think not!).

Unnamed sources tell me that, as the Mayans nearly predicted, 2012 will be the year when misusing vendor prefixes will no longer be tolerated and manufacturers bastardising CSS Media Queries to do UA-sniffing will not go unnoticed.

Don’t believe me? Here is an artist’s impression of an actual photo of Tim Berners-Lee summoning his standards-avenging attack ninjas.

Cartoon Ninja using a computer with W3C logo on lid. Japanese text.

Tremble, proprietary-lovin’ developers!

Reading List

The last reading list of the year is a bumper one, so you have plenty to read over the hols. Enjoy!

Me

HTML

CSS

JavaScript

Multimedia

Data

Mobile

Kerrrazy Shit!

Reading List

In amongst all the festive rancour, there were a few interesting sites I saw in the last week or so.

  • Notes on Designing Websites for the Asian Market by Yours Truly.
  • MPEG-DASH is the first International Standard for dynamic adaptive streaming of multimedia content over HTTP. It will be interesting to see what the royalty/ licensing situation will be.
  • I don’t agree with everything Faruk says in The Threat Against the Web, but wholeheartedly applaud “The web will only thrive as long as the web is not owned by any one entity; not owned, not controlled, and not defined”.
  • On the subject of the constantly-embattled Open Web, Google offered patches to allow their super-whizzo! invented-in-secret Dart language to be in WebKit. Oliver Hunt of Apple objected: “As the 90s demonstrated such “features” are bad for developers, and bad for the open web. This may not be apparent to people who have not spent years working in the environment but random additions frequently cause significant pain down the road” and adding adding “it fragments the web” and risks “turn[ing] webkit into the engine that everyone hates because of all its unique “features” that break the open web, a la certain browsers in the late 90s”.
  • W3C: Open Web Platform Weekly Summary – 2011-12-05 – 2011-12-11 (worth an RSS subscription)
  • Shapecatcher lets you draw a shape and tries to match it to any of 10,877 unicode characters.
  • Still life: Bent objects – The secret life of everyday things

Notes on Adaptive Images (yet again!)

All the cool kids are doing responsive design, it seems. This means fluid designs, having some hot media query action to reformat your layout depending on screen size, and ensuring your images are flexible so they don’t break out of container, generally by setting them to {max-width:100%;}.

Having images scaling down presents a problem though, if you’re a performance-minded sort of chap(ette). Why send a 300K 400 x 800 image that would look lovely on tablet device attached to wifi, but which takes ages to download on a 3G phone, and which gets resized by the browser to fit a 320px wide screen? Not only are you wasting your user’s bandwidth and time, but not every browser is created equal and not every resize algorithm makes pleasing end results. The CSS 4(!) image-rendering property can help with this but it only hints to the browser.

Sending the right-sized image to devices without wasting bandwidth is one of the knottiest problems in cross-device and responsive design at the moment. In the 24ways advent calendar series of articles, the subject has been discussed twice in eight articles (by Matt Wilcox and Jake Archibald). There are numerous other techniques, as well, such as tinySrc and the Filament Group’s Responsive Images.

All these are very clever, different solutions to solve the same problem, and they all rely on scripts, or cookies, or server-side cleverness or (in the case of Jake’s ideas) dirty hacks and spacer GIFs. I’m reminded of Image Replacement techniques from more than 6 years ago, which were over-engineered solutions to the problem better solved by CSS web fonts.

Let’s recap. We have several images, of different sizes, and want to send only the most appropriately-sized image to the browser. The circumstances differ. The canonical use case is to send smaller, lower-resolution images to smaller screen-sizes on the assumption that connection speed is slow and they have low-resolution displays. This isn’t the case, though. Some people are using retina displays on fast wifi networks. SO, while currently CSS Media Queries allow us to detect screen width and pixel density, we need new media features such as network speed/ bandwidth.

The DAP is working on a Network Information API, there’s a Phonegap version for native apps, and a Modernizr detect, but using script for this seems much harder than being able to access it via Media Queries, and if you just want to rearrange CSS layout, CSS is the place to detect it. (Purists may argue that network connection isn’t a characteristic of device, but in your face, purists!)

Once you have a media query, you can swap images in and out using the CSS content property:

<img id=thingy src=picture.png alt="a mankini">
…
@media all and (max-width:600px) {
 #thingy {content: url(medium-res.png);}
 }

@media all and (max-width:320px) {
 #thingy {content: url(low-res.png);}
 }

@media all and (network-speed:3g) {
 #thingy {content: attr(alt);}
 }


A browser that doesn’t support Media Queries, or doesn’t report “true” for any of the Media Queries shows the picture.png, which is the src of the img. A browser that is less than 600px replaces picture.png with medium-res.png. A 320px or narrower browser replaces picture.png with low-res.png. A browser that is only connected via 3g replaces the image with its alt text.

I first researched this technique in 2008 as a way of doing image replacement without extra markup (ironically enough). The first two media queries only works in Opera and Chrome at the moment, as they’re the only browsers that fully support content without :before or :after. (The network-speed media query works nowhere as I just made it up).

Recently, Nicolas Gallagher experimented with generated content for responsive images, and unfortunately discovered that there are no advantages to the technique because browsers always download picture.png, even if they never show it because they immediately replace it. Perhaps this could be optimised away by browsers, but there would still be the double-download problem with current browsers.

My mind turned to HTML5 video. Here we have an element that has the ability to specify multiple sources (because of different codecs) and can also switch sources according to media characteristics. It borrows syntax from Media Queries but puts them in the HTML:

<video>
<source src=high-res.webm media="min-width:800px">
<source src=low-res.webm>
<!-- fallback content -->
</video>

I firmly believe that if something as new-fangled as video can be responsive in a declarative manner (without needing script, APIs, cookies or server magic) then responsive images should be similarly simple.

Previously, on the mailing list, a new <picture> element was proposed. I mashed up that idea with the already-proven video code above and came up with a strawman:

<picture alt="angry pirate">
<source src=hires.png media="min-width:800px">
<source src=midres.png media="network-speed:3g">
<source src=lores.png>
   <!-- fallback for browsers without support -->
   <img src=midres.png alt="angry pirate">
</picture>

This would show a different source image for different situations. Old (=current) browsers get the fallback img element. As I said, this is a strawman; it ain’t pretty. But it would work. (It’s discussed in my recent Smashing Magazine article HTML5 Semantics.)

I prefer the media queries to be in the HTML for two reasons: you don’t need to have ids or complex selectors to target a particular image, and (more importantly) many content authors use a CMS and have no ability to edit the CSS. (Although the nasty <style scoped> could solve this.)

On the other hand, I might be over-engineering the whole problem. I chatted informally with my colleague Anne van Kesteren, glamorous Dutch WHATWG inner circle member. There’s a school of thought that says everything will be 300ppi and networks will be fast enough, so this is really an intermediate problem until everyone starts using highres graphics and all displays go from 150 to 300. Standards are long term, and by the time we have a standardised version, the problem might have gone away.

What do you think?

(Matt Machell pithily pointed out “if only browsers hadn’t forgotten the old school lowsrc attribute for images“.)

Looks like our chums at WHATWG are discussing this too.

Reading List

Links’n'stuff that I’ve tweeted, for those who don’t spend their days on twitter but who work instead.

HTML5, markup

Groovy webdev stuff

CSS

Vendor prefixes

Misc

Creative JavaScript with Seb Lee-DeLisle

One of the many joys of going to Fronteers 2011 (even more than seeing Jake Archibald in a mankini) was Seb Lee-DeLisle’s presentation “CreativeJS – beauty in the browser”. Watching sexy particle systems, using mobile phones as pixels and playing NyanCatch was fun and exciting.

I’m a JavaScipt n00b, but an old hand at programming, which I taught myself in the 80s by coding visual games like space invaders and lunar lander. So when I heard that Seb was giving a two-day workshop in Leeds on how to code creative visual effects and games, I decided to go along.

Seb didn’t start at the very beginning; it’s assumed that we have a text editor, a web inspector (I was using Opera Dragonfly, of course) and that we know what variables and loops are. There wasn’t much talk of prototyping and inheritance either – the emphasis was on the making rather than the theory.

We looked at canvas, how to make simple shapes and simple animations. Then we used Seb’s simple library to add drag, velocity, gravity and randomness to particles, all the while building pretty effects that responded to the mouse. We learned canvas rotations and transforms (which I hadn’t really bellyfelt before) by making a generated tree (which I topped off with random cherry blossom).

We learned how to code the game Asteroids, with a reminder of trigonometry that shocked me: who knew I’d ever need SOHCAHTOA or the Pythagorean theorem in real life? This also helped us learn how to make natural-seeming physics.

We all had a brief foray in webGL, albeit abstracting away most of the horrors via Mr Doob’s THREE.js.

It was a great fun course. Seb’s an engaging and effective teacher and I feel much more confident with my JavaScript now (I even suggested an optimisation to Seb’s collision detection code!). Thanks to Seb, Clare who co-organised it, and my fellow attendees.

If you’re looking for an “in” to JavaScript, and you learn by mucking about and seeing what comes out the other end, sign up to Seb’s next course.

Introducing HTML5 Second edition

Yay! The first, the original, the sexiest, the motherflippin’ brownest book on HTML5, Introducing HTML5 is out in second edition!

What’s new?

It’s bigger, baby – having swollen from 223 pages to a tumescent 295 pages – for less than the cover price of the original. Apart from a photo of the snogtabulous uberhunks™ that are its authors on the front cover, and the inner colour changing from orange to blue, what are the highlights?

  • Errors are corrected and it’s all re-read and updated
  • It’s been fully re-edited, re-proofed and re-indexed
  • Bruce has changed his mind about the <nav> element and now advises you don’t use it bloody everywhere
  • The multimedia chapter has added information on <track>, getUserMedia, webRTC
  • Even more detail about how to get more out of geolocation
  • More storage methods and techniques, including the new IndexedDB storage API
  • We now have full examples on how to use Server Sent Events
  • Updated detail on offline applications, gotchas and debugging tips
  • A full new chapter on polyfills, what they are, how they work and how to use them

Updated launch photos?

You bet!

Remy, resplendent on the bed like a Botticelli painting. or a jelly botty picture.

bruce, looking elegant and intellectual in a lime green mankini

So buy the book already, or we’re coming round your house dressed like this to ask why you haven’t. And don’t forget to join in the fun by sending a photo of you with a copy of the book, doing your O-face, or wearing in mankini for inclusion in the HTML5 gallery of gorgeous guys and groovy gals.

Thanks to Krijn Hoetmer for the mankini. Next time I’m turning the heating on.

The return of <time>

If you’re interested in this stuff at all, you’ll probably know this, but for the sake of completeness, the <time> element has returned to HTML5 after it was removed from the specification.

I reserved cheering until in case it was grudgingly returned to the W3C spec but not the WHATWG spec, as I don’t particularly want to see forked specs.

The old version of the element is now in the W3C spec, but not in the WHATWG version. But I’m not worried; it appears that it will be added as a New!Improved! element with some extra features to make it actually useful that I’ve been asking for since March 2009.

Editor Ian Hickson wrote

A few weeks ago, I replaced <time> with <data>. We got feedback from many people saying that there were use cases that <data> didn’t handle, and requesting <time> be left in the spec. It turns out what people were asking for was not quite the old <time> element, it was more like a variant of <data> that was specifically for <time>. (The old <time> was specified as doing locale-specific rendering, had a more or less useless API, and only supported a small set of data and time syntaxes.) Tantek made a proposal for how to handle these use cases, which I intend to add to the spec ("the <time> element is dead, long live the <time> element").

Indeed. <time>2.0. Time, after time.

Hickson has also hinted that we might get a <geo> element, too (as I suggested in my HTML5 Semantics talk at Fronteers.)

(Let’s just hope Tantek doesn’t neglect the vital use-case of 4 simultaneous days in 24 hrs advocated by Gene Ray’s Timecube theory.)

Goodbye HTML5 <time>, hello <data>!

This post is obsolete. See The return of <time> for the latest information.

It’s with great sadness that I inform you that the HTML5 <time> element has been dropped, and replaced by a more generic – and thus less useful – <data> element. The pubdate attribute has been dropped completely, so there is now no simple way to indicate the publication date of a work.

Editor Ian “Hixie” Hickson explained:

There are several use cases for <time>:

A. Easier styling of dates and times from CSS.

A way to mark up the publication date/time for an article (e.g. for
conversion to Atom).

C. A way to mark up machine-readable times and dates for use in Microformats or
microdata.

Use cases A and B do not seem to have much traction.

Use case C applies to more than just dates, and the lack of solution for stuff
outside dates and times is being problematic to many communities.

Proposal: we dump use cases A and B, and pivot <time> on use case C, changing
it to <data> and making it like the <abbr> for machine-readable data, primarily
for use by Microformats and HTML’s microdata feature.

I think this is a bad decision.

<time> was originally dreamed up to correct an accessibility problem with microformats that James Craig and I raised in 2007.

While Hixie says it hasn’t had much traction in microformats. Ben Ward, a platform developer at Twitter and microformats admin, says “We’ve had time documented on the wiki HTML5 page for ages, some parsers had experimental support. But <time> wouldn’t be able to progress into being a requirement or even recommendation for Microformats until HTML5 had that status”.

It’s also used on reddit.com and github.com (with Alexa rankings of 112 and 549, respectively – hat-tip, Mike Taylor), the Boston Globe and default WordPress theme, twentyeleven (which has a mere 2.6 million installs). It’s also used in the Atlassian suite of products: JIRA, Confluence, Bamboo and BitBucket (hat-tip Ben Buchanan). Drupal developers have been adding it to the core theming systems, too.

<time> (or its precursor, <date>) has an obvious semantic (easy to learn, easy to read). Because it’s restricted to dates and times, the datetime attribute has a specific syntax that can be checked by a validator. Conversely, <data value=”"> has no such built-in syntax, as it’s for arbitrary lumps of data, so can’t be machine validated. This will lead to more erroneous dates being published. Therefore, the reliability and thus the utility of the information being communicated in machine-readable format diminishes.

The <data> spec says “A script loaded by the page (and thus privy to the page’s internal convention of marking up dates and times using the data element) could scan through the page and look at all the data elements therein to create an index of dates and times.”

This is a retrograde step from the <time> element that uses a wider standard/ convention for dates, such as ISO8601 because now the script must be “privy to the page’s internal convention”.

<data> as an element is for public consumption, eg for crawlers, search engines, microformats/ microdata parsers. Convesely, data-* attributes are private (only for scripts on a page, not external crawlers: “These attributes are not intended for use by software that is independent of the site that uses the attributes.” ). This is highly confusing.

I’ve added these points to a collaborative notepad set up by Eric Eggert, at his request.

But I have little hope that <time> and pubdate will be restored, even though most comments on the bug in which Hixie changed the spec were negative.

But sing along with me in my Cher costume, and we might just change Hixie’s mind.

Added 20:06 Oct 30: The Mighty Steve Faulkner filed a revert request.

Usual disclaimer: personal opinion, written on Sunday night, not Opera, etc etc.

Other discussion

Update 4 November 2011

At an HTML Working Groupp meet last night, it was decided to re-instate <time> and even extend it to encompass things I complained in 2009 were lacking — “fuzzy dates” like “1965″ or “February 2008″ and durations.

However, it remains to be seen whether it’ll be reinstated in both the W3C spec and the WHATWG versions or just the W3C. So I’ll delay celebration until then.