samwood.org

Video in XHTML

Real smooth?

I’ve been experimenting recently with the best way to embed video in XHTML. You’re probably wondering why not just use HTML5 with the <video> tag? The primary reason is that I avoid using HTML5 in any of my pages, because it’s a huge, constantly changing specification that (if you will humor me and my conspiracy theories) Google deliberately makes it difficult to keep up with so no one can build a serious competitor to Chrome. XHTML is old, well understood, well supported, and easy to implement.

The other reason is that I don’t really think the <video> and <audio> tags were necessary or desirable additions to HTML. Not only are they redundant with the <object> tag that has existed since HTML4, but they are inappropriate to the language in much the same way the old presentational tags were. They explicitly introduce behavioral attributes—autoplay, controls, loop, etc.—which should be handled by JavaScript (or left up to the user agent). HTML is structure; CSS is presentation; JavaScript is behavior.

Where’s the cave-man?

Really the only roadblock to using <object> on its own is that some user agents will autoplay embedded video, which makes sense from the perspective that the <object> is simply rendering whatever data it finds, but this is usually not what you want to happen. But, as I said earlier, having a video sit statically behind a thumbnail until a user clicks on it is behavior, so this problem is best solved with a few lines of JavaScript. Before doing that, though, it is always better to consider what the best way of doing this without JavaScript is, and enhance progressively from there. The goal is to prevent the video from playing until the user clicks on it, and the simplest way to do that is with a hyperlink, so the plain HTML document will have a thumbnail image that links directly to the video as its own resource.

Now, for clients that do support JavaScript, I need to do two things: (1) add custom click events to each hyperlink that leads to a video, and (2) define a function for that click event that will cause the videos to play embedded in the page. (1) can be accomplished by adding a custom class to the video hyperlinks (I used media), then iterating over every <a> element with that class to register the click event. (2) can be done by replacing the <a> element with an <object> element whose data URI is set to the same value as the <a> element’s href.

This way, the semantics of the static HTML are clear, the page works in an expected way for both types of clients, and no one notices anything strange. The <a> tag ensures that all types of clients have a way to access the video, but if the JavaScript runs, it effectively says, I am going to do this hyperlink’s job for it, so it is safe to deactivate it.


Valid XHTML Basic 1.1! Valid CSS level 2.1! This website is licensed under CC-BY-ND.