Friday, April 23, 2010

Why declarative animation should be in the DOM and not in CSS

Note: This blog post did reflect my opinion at the time of writing. Since then technology has evolved and now this has become less of an issue. I will leave the post online, but if you came to learn about how to do animation today, reading will be a waste of your time.

A little more than a year ago Safari introduced experimental support for CSS based animations, to compliment transformations and transitions. I have no gripe with transitions and transformations, but I think animations belong in the DOM and not in CSS. My main argument is that animations will most of the time be triggered by DOM-events, and during at least the next five years most CSS-based animations will be duplicated using classic DOM-methods anyway. The purported separation of animation (for designers) who are supposedly scared away from scripting is not a valid argument, since they are going to use libraries anyway. (And, frankly, the CSS animation syntax in itself looks quite scary to most people!)

Originally, this started out mostly as a gut feeling, and the arguments that I've made on the W3C mailing list are varied and admittedly a bit confused. I was thinking out loud more than I was presenting a coherent argument. Hopefully this blog post will come across as more reasonable!

I also believe that this discussion needs to be known outside of the CSS working group and the participants on the www-style mailing list. Specifically, it needs the input of developers of JavaScript libraries and normal web developers. These are the people who will be affected the most by any decision. (I am providing an abundance of links to the discussion on the mailing list for context.)

CSS animation – the good parts

A few aspects of the CSS animation proposal are brilliant and not of dispute:

  • Declarative syntax. Designers specify what effect they want, not how the browser should achieve it.
  • Hardware acceleration. Animations get smoother, faster and less CPU-draining. The GPU is optimized for this and can perform the calculations using only a fraction of the power and time a CPU would take to do the same number crunching.

When I am asking the CSS working group to reconsider CSS animations I am not in any way trying to take away these two strong points. I am firmly pro having GPU-accelerated, declarative animations in the browser. I just think the DOM is a better fit for them.

What will be animated?

CSS has no events, it has states. Basically it knows the focused and unfocused state on links and widgets and if a pointer is hovering, clicking ("active") or not hovering over an element. While exeperimenting with the CSS animation syntax, the working is producing examples using these states. Ironically mobile devices are one of the main reasons why CSS animations were originally thought up, and they rarely have a pointer, and CSS is not really equipped to handle touch events.

It can safely be assumed that 99 % of all real world use cases for animation will be the result of user or server interaction on some part of the document that is not being animated. The user clicks a button and a div will slide into view. The user presses a key on his keyboard and text will wiggle and bounce. Data is sent back from an AJAX request, and the received data will appear through an attention grabbing sliding effect.

Currently the only way to achieve these real world use cases is by adding or removing class attribute values. Thus we have scripts that will trigger animation in the DOM and the actual design of the animated effects in CSS. Conceptually this is nice. Separation of logic is a good thing™. However, in real world practice this will not be so neat.

Events confusion

Even though there are no events in CSS, there is discussion about having animations running upon entering a state, while being in a state and when leaving a state. These are not events in a technical sense, but outside of the W3C working group, most developers will be really confused about the difference. Such precise knowledge is not found in abundance! If a specific application need to differentiate between these, it is by far easier for developers to use the more familiar DOM events.

Having some animations run because they are affected directly, e.g. on hover, some animations run because they are triggered by a scripted change of className, and in both cases also have animations that may run entering, during and leaving states looks like a recipe for unmaintainable and confusing development. It is way much better to trigger all events from one place only, and that place can only be the DOM.

How to implement animations in a library

OK, you are building a little library to animate stuff. What do you do? I suppose the following:

  1. First you capability detect support for declarative animation. That in itself would be easier if it was in the DOM, but it is at least doable now. But not in a neat fashion. Score one against having animations in CSS.
  2. If CSS-animation is indeed supported, you will wrap your animate function around className switches. Doable, but not neat.
  3. If CSS-animation is unsupported, you fall back to old school timed manipulation of the style attribute.
    • However, using the animation parameters from the CSS-file is a huge impracticality. You must find a way to read all CSS-files, parse them and interpret the cascade, the specificitivity of all animation rules and convert that information into timed logic. This is impractical, slow and CPU-draining and fragile.
    • The CSS Object Model (CSSOM) will not alleviate this problem. Browsers that need to parse the animation rules are the ones that neither implement animations, nor the corresponding CSSOM.

Alternatively, the author is required to re-specify the animation once again, now using a syntax for the fallback. We thus get code duplication, with all the error proneness and maintenance problems that follows from that approach. But it is the only approach currently available with reasonable results.

It can safely be said, that CSS-animations are not backwards compatible in any reasonable way. And we are going to need backwards compatible solutions for almost another decade or so.

What about progressive enhancement?

Using progressive enhancement we can deliver CSS-based animation to browser that support it, and non-animated but still usable content to the rest. Problem solved, is it not?

I like progressive enhancement. I teach it and I practice it. However, there will be a great number of real world customers that will insist upon having animations in both the brand new cutting edge browsers and the legacy ones. As least as long as more than 10 % of their visitors use them. We can preach all we want. This scenario will face the real world developer way too often.

Animations will be used to convey information as well as for eye candy. Not having a scripted fall back will not be an option for such use cases either. In real world web development, progressive enhancement can not be called upon to be a panacea, how appealing that thought ever may be.

What else will be hard to do using a CSS approach?

In real world use cases developers are also going to want to manipulate animation and keyframe properties, as well as programmatically create animations from scratch. Using the CSSOM this can probably be done in browser that support animation but once again the fallback for legacy browsers will be very hard to achieve.

What is my counter proposal

I have barely begun thinking about this issue, so any propsal I have at the moment should not be regarded as a final suggestion. In order to keep the separation of concern between designers and developers – for those situations where one has the luxury to keep them separate – animations must be easy to define with a CSS-like syntax. JSON fits that requirement quite well. The method to start an animation could be called runAnimation. It might return a value that I can store in a variable in order to manipulate or cancel the running animation. Another way to manipulate it would be by altering the animation properties. For convenience, there should also be a method to stop all running animations on an element.

Here is an example, recreating the effect from Surfin' Safari's announcement:


// Keep the JSON objects in a separate file for designers to fiddle with

var bounce = {
    "from" : {
        "left" : "0px"
   }
   "to" : {
       "left" : "200px"
    }
}

var myAnimation = {
 "animation-name" : "bounce",
 "animation-duration" : "4s",
 "animation-iteration-count" : "10",
 "animation-direction": "alternate"
}

// Keep these lines in another file for the JavaScript guy/girl to fiddle with

document.getElementById("foo1").onclick = function() {
    document.getElementById("bar").runAnimation(myAnimation);
}

document.getElementById("foo2").onclick = function() {
    document.getElementById("bar").stopAllAnimations();
}

// Example 2
// Keep the JSON objects in a separate file for designers to fiddle with

var pulse = {
    "0%" : {
        "background-color" : "red",
        "opacity" : "1.0",
        "transform": "scale(1.0) rotate(0deg)"
    }
    "33%" : {
        "background-color": "blue",
        "opacity" : "0.75",
        "transform" : "scale(1.1) rotate(-5deg)"
    }
    "67%" : {
        "background-color": "green",
        "opacity": "0.5",
        "transform": "scale(1.1) rotate(5deg)"
    }
    "100%" : {
        "background-color": red,
        "opacity": "1.0",
        "transform" : "scale(1.0) rotate(0deg)"
    }
}

var pulsedbox {
    "animation-name": "pulse",
    "animation-duration": "4s",
    "animation-direction" : "alternate",
    "animation-timing-function" : "ease-in-out"
}

// And here comes the DOM-parts, this time using JQuery for easy iteration

$(".pulsedbox").each(function() {
    this.runAnimation(pulsedbox);
});

As stated above, my counter proposal is not a finished product in any way. It merely is intended to serve as an illustration to an alternative approach. The technical merits or defeciencies of that proposal is in itself not really something that should guide the general discussion about how to implement declarative animation. The principles on which I draw the conclusion that the DOM is a better fit is the true talking point here.

Now I am especially interested in hearing the opinions from the DOM-scripting community!

Monday, March 22, 2010

PPK is wrong, vendor prefixes are a necessary evil.

Yet another considered harmful essay has hit the web. This time it is PPK, a well known JavaScript guru and very influential author that has written it. And I get to disagree with another one of my heroes. (Just recently I have disagreed with Rasmus Leerdorf on the naming of the next major PHP version...)

Basically PPK is like many others fed up with writing the same rule 2, 3 or even 4 times. You know the drill:


-moz-border-radius: npx;
-webkit-border-radius: npx;
border-radius: npx;
Add in a few (-ms-)filter as well and it's a nightmare. And the CSS-validator is not configured to ignore these, even though they are not errors per se. It is sure easy to echo PPK's sentiment. But I believe he is wrong, and fortunately I am not the only one.

Proposals do change

Case in point is border-radius and gradients. Mozilla could not just drop -moz- from border radius, since their 6 year old implementation is not aligned with standards. Webkit can not drop the prefix from their gradients rules, since the standard probably - please note that word, probably - will look like Mozillas implementation.

I also note that he has put the non-prefixed version of a rule before the prefixed ones, which is not optimal for the very same reason. A problem I have dealt with in an earlier blog post.

Experimental versions are needed for things to move along. Without them very few people will be able to experiment and improve the proposal. This is a real need, this is a real problem.

Contrary to what PPK says, vendors do not simply copy each other. They often start that way, end then they run into questions like what about... and they will have to discuss and test and decide and make changes. Both to the implementation and the spec. Such discussions take place on the W3C mailing lists all the time.

Standards must be standards

PPK dislikes vendor prefixes because they seem to be the opposite of standards: Vendor specific rules, code forks, similar to browser sniffing in JavaScript.

But what he is proposing is effectually doing away with the entire W3C process. Yes, it is slow and burdened by politics. But if we drop vendor prefixes that will mean that as soon as a browser puts out a new technology it, by virtue of being first, has decided unilaterally what the syntax should look like and how it should work in every browser. This is not a standards process, this is in fact the opposite. First to market rules and everyone else be damned!

Experimental versions of future standards are a good thing, since they allow for real discussion and much more thorough standardization. One of the reasons standards are moving slowly is that today they are much more detailed, much more tested and therefore much more reliable.

This is not unique to web standards. Consider IEEE802.11n and the fact that we for a couple of years had draft version equipment on the market. Good or bad? It made the final implementation better, so yes it was good. And a necessary evil as well.

There must be room for errors

Webkit has not copied Mozilla's implementation of border-radius and Mozilla has not copied Webkit's gradients. Having discussed the proposals changes have been made, lessons have been learned and this has happened in real life.

If a vendor must not use prefixes it would take forever to get to a place where they would be confident enough to put out a new technology. Opera and Microsoft may skip the prefix for border radius, since thanks to Mozilla that 6 years ago put out an experimental implementation and thanks to Webkit, that 3 years ago put a out a slightly different experimental implementation, the standard has now reached Candidate Recommendation status and web authors demand the technology, because we have been able to experiment with it!

If it had not been for prefixes, only a very few people would actually have bothered to download experimental browsers and try this out. That is our only other option. The word would not have spread and demand had not been built up.

Is summary. PPK, I love your work and have tons of respect four you. But in this case you are wrong. I will not shout long live the prefixes, since I wish that every prefixed CSS rule should have short life. But I want that short life to be productive.

Thursday, September 10, 2009

Pedagogic validation of HTML

I have been trying to make HTML5 better for education by participating in the HTML5 effort at WHATWG for a few years. Recently also joined the W3C HTML5 Working Group. One of the things that might come out of this effort is an option in the HTML5 validator for pedagogic validation. I will try to explain what such an option should check for, and how it will be beneficial to teaching web development.

I have previously written about what I call the value of false XHTML. Now I have been joined by the HTML5 superfriends, who request an option for easy polyglot validation. Henri Sivonen, who no doubt is a parsing rules genius and exceptionally knowledgeable, basically replied that such a thing is very hard, and contains so many minute details, that it might be of no value. Did you know that a line feed immediately following the starting pre-tag is forbidden, when using XML parsing rules? I most certainly did not. (And I am still a bit unsure if I got it right...)

I usually also skip the tbody-tags when I do tables, but they are nevertheless automatically inserted into the DOM in HTML, just like head and body is. That will not work for a true polyglot document, since in XHTML the DOM will not be the same. Henri also suggests that using XHTML syntax might lead to a false understanding, as if one would believe that <script /> would be possible to write in normal HTML.

I commented on Zeldmans blog that from my perspective these are non issues. Let me tell you about the everyday problems I encounter as a teacher of markup languages, in addition to what a normal validation would reveal:

  • Students forgetting to quote attribute values, even though they contain multiple words.<img alt=My dog>
  • Students messing up the balance of the quotation marks: <img src="foo.jpg alt=My dog">
  • Students messing up the DOM since they do not (yet) know all the rules for when an element is implicitly closed by another elements starting tag.
  • Students using document.write (and eval) in their scripts - yes I explicitly tell them not to, but they don't always listen, do they?

For reasons like these I tell them to use XHTML syntax today, since that will catch most of these errors.

document.write and eval is outside the scope of HTML validation, but ECMAScript 5th edition strict mode and JSLint will take care of most such problems. What I would like is for HTML validation to have similar checks, checks that enforce good habits and helps to avoid rookie mistakes.

What's the problem with true polyglot documents then?

  • The minutiae. The stuff Henri Sivonen rigthly reminds us of. The stuff that should be saved for a later class, since it is so highly technical and frankly will scare some away from coding by hand.
  • The boolean attributes. Some HTML5 form elements may have a lot of those! Allowing them to exist in their shortened form would mean less markup to type (= happier students, less bandwidth required).

As you see, I do share some of the concerns about XHTML syntax. But today the benefits clearly outweigh the drawbacks, from a pedagogic perspective. But this naturally leads me to the conclusion that there should be some middle ground, a way to specify a pedagogic profile for validation - and voila - Sam Ruby has started to work on such a feature!

I will now explain what features such additional checks should have, according to my experience, and how they are beneficial. I will grade my suggestions from 1 to 5, in rising order of importance.

Avoid implicit rules

But check that what's explicit comply with them. One should as a newbie see a 1:1 correlation between the DOM and the markup.

All elements should be explicit

This would mean that:

  • Root-element (html), head and body tags should not be optional (grade 5).
  • tbody tags should not be optional (grade 1).

In order to avoid making classes boring, I usually teach HTML together with some CSS from day one. I do not teach HTML first for a few weeks, and then I teach CSS. Besides being boooring, this will lead to some students starting to use presentational elements and attributes, because they will really want to have design features from day one.

CSS rules (usually) apply to the DOM, and not the markup, e.g. you can not have have a table#foo > tr selector even if there are no tbody-tags in the code. The student would think that a tr is a child element of table, since implicitly added elements might not be taught until later. It is, however, not usually so that one starts using tables early on - since they are not used for layout when I teach CSS in conjunction with HTML, so I can live this particular check not being implemented, hence it is graded at 1 only.

Explicitly grouping meta data about a document in the head section, and specifically being able to put some scripts in the head and other scripts in the body, is however very essential. In HTML5 we might also see scoped style-elements, which makes the use of explicit head and body tags even more important.

All elements must be explicitly closed
  • All normal elements must have closing tags.(grade 5)
  • Void elements must have a trailing slash. (grade 3)

The use case for closing tags is really simple. Besides making things easier to understand, it also alerts students about implicitly closed elements. If they would try to include a table in a paragraph the validator would complain when it encounters the closing p-tag. For such reasons I tell my students that closing tags are mandatory, and I want a simple way to enforce that behavior.

All non-shortened attributes must have their values quoted. (grade 5)

As I've said above, this is a very common error. In the worst case scenario it might lead to very unexpected results. Look at this example, where the value attribute is supposed to contain the words Login name:

<input type=text value=Login name name=login>

This code snippet actually produces a DOM as if the markup had read:

<input type="text" value="Login" name="">

Arguably, enforcing quotation marks also leads to better readability.

There are a few attributes that might be exceptions to this rule:

  • If the only possible value is an integer.
  • If the only possible value is a keyword containing only US-ASCII letters.

However, enforcing good habits takes precedence over any other concern. I always start teaching the hardest possible rules, and the I gradually relax them. This works better than doing it the other way round.

Attribute values that contain > or = probably are errenous (grade 3)

<abbr title="Et cetera>etc</abbr>
<abbr title="Et cetera class="foo>etc</abbr>

These are two examples of mismatched quotation marks., Yes, it happens a lot that I look over a shoulder of a student and say that they have forgotten to close the attribute - even though they have syntax highligthing on in the editors. (Not everyone's a genius and some are color blind!) If I could have tools that took care of the easy stuff, I'd be able to spend more time explaining the real issues and everyone in my classroom would be happier.

Since at least the second error might be confused with valid use, this behavior probably should generate a notice, not a real error. Using the equal sign in an attribute value might be an indication of a real error, please check that your markup is correct.

Many of these errors would probably get reported even with todays validation rules. I am gunning for those edge cases where two errors even each other out so that they mask each other.

Language must be specified (grade 5)

This one is self-explenatory. There really should be a lang-attribute set on the root element. This actually should be a regular conformance critera, but since such a rule will wreck a lot of currently valid sites, that is probably not doable.

The alt attribute must always be present om images. (grade 5)

While the jury (maybe) still is out on whether this should be a regular conformance criteria (as I think it should) or not, at least the following could be said without any hesitation or doubt: No single argument against a mandatory alt-attribute applies to the learning situation. Even if we say that sites like Flickr should be able to be conformant even if users do not spply usable alt text and having considered every other option it is decided to make the alt attribute optional, those use cases for sure do not apply in the class room! If HTML5 eventually would go down that route, for this reason alone a pedagogic profile in the validator has earned its right to exist.

I am actually a bit reluctant to add this point. I fear it might re-open a can of worms and be taken as an argument against having alt as a mandatory attribute, since those who wish would now have a way of checking for its existence. However, I hope that everyone realizes that this is not the same discussion. My only point is, that if worst should come to worst, this feature is necessary.

What else?

I am going to give this some thought — and Sam Ruby a few initial test cases… After which I might revisit this subject and alter my list of things to test. Of course all feedback is welcome!

One thing that I've thought about is a check for code indentation. But first of all it is probably not possible to check for this in a reasonable manner. And would it be possible to agree on a standard? Nah! I don't think so.

P.S. If someone wonders why my blog has the word Thinkpad in its name, I do still have an ambition to document my joys and woes about using Fedora Linux on my Z61p (and on my still un-bought W700…). Patience, patience.

Friday, August 21, 2009

Web Education Rocks Indeed

Aarron's hand pointing to the OWEA vision taking shapeI had the privilege and pleasure to attend the WE Rock Summit. To me the meeting was a perfect illustration about the power and limitation (sic!) of the Internet. Living in Sweden and working for a public school where one does not have access to an abundance of money (to say the least), I have not been able to participate in SxSW or similar conferences in the USA. In fact, my only contact with the other participants, except for Chris Mills from England, had been through the net. That fact had no stopped us from getting to know each other and organize around the vision of bringing the best possible standard for Web education to schools, colleges and universities around the world.

OWEA Summit in progress onboard the Delta Queen Meeting in person was a lot like meeting old friends. We did not need to connect instantly, we were already connected! We did not need to get off to a flying start in our work. We had already started. The fact that a lot of discussions were tentative and that a lot of resolutions still remain to be done, is not an indication about anything but the fact that what we are trying to do is to a large extent an adventure into unchartered territory. To launch a Web Education Organization at this level is simply an undertaking that no one has made a realistic attempt to do before OWEA.

Leslie Jensen and her team at the Hunter MuseumAt the same time being able to meet in person took our productivity to a whole new level. There simply is a level of interaction that is made possible by being in the same room. For this opportunity I am deeply grateful to our sponsors. What they made possible was perfectly realized through the skills and the personal care of the local hosts in Chattanooga. Thanks to their welcoming attitude, personal warmth, attention to detail and zeal for our common vision, our meeting never felt like an ardous task. Productivity in discussions remained the product of enthusiasms. Yes, it was intense, and yes, we got tired. But we had fun all the time!

Me at Point Park leaning against a gun from the Civil warWhen the summit was over I stayed a couple of days. I attended a service at Olivet Baptist Church — since I wanted to experience real gospel worship. I looked at city sites like Bluff View and a few parks. I also went to the Tennesse Aquarium and Point Park on Lookout mountain. To round things off I was met with great hospitality from Aaron and Cathy Gustafson during Monday. When our faithful driver, Shaun, left me at the airport on Tuesday, it felt like I'd been away for a month, not a week.

What I bring home is fond memories of meeting wonderful people, renewed passion for Web Education and a great hope that OWEA will make a difference, yes, even make the world a slightly better one! And a longing to return for another visit to Chattanooga!

P.S. More photos are posted on my Flickr page.

Sunday, July 19, 2009

The value of false XHTML

I believe there is a value to using XHTML syntax for documents sent to the browsers as text/html. That seemed like the normal thing to do just a short time ago. Now it is increasingly being met with skepticism and even ridicule. I believe I've encountered every XHTML myth busting argument there is from the good people in the WHAT WG cabal, but I still see a value in using XHTML syntax. My arguments are not centered around forward compatibility, extension mechanisms or XSLT, even though they could apply — server side. My reasons for using XHTML syntax is to avoid errors, misunderstandings and rookie mistakes. Since I teach web development for a living I encounter a lot of those.

The issues

HTML 5 is clarifying what XHTML really is. A lot of web sites are using an XHTML doctype, even though the code will be parsed as just like ordinary HTML, i.e. they use false XHTML. But draconian error handling, including Unicode errors, altered CSS applicability, the breaking of 99 % of all JavaScript code in existence, including all major libraries, and of course, Microsoft's not implementing true XHTML at all, all of this will continue to make true XHTML a non option for anything else but experiments and edge cases for the foreseeable future.

Put in one sentence: Specifying an XHTML doctype does not make a document XHTML. As we know by now, the doctype serves only one purpose in the browser and that is to trigger standards mode (assuming a good doctype). And if a browser treats XHTML 1.0 strict exactly the same as it treats HTML 4.01 strict, why not opt for the latter? And as HTML 5 has no other mechanism to specify XHTML other than the MIME-type, what one might chose to call false XHTML is no longer possible to use.

On the other hand, XHTML syntax that previously was illegal in HTML, like explicitly closing void elements (br, hr, input, meta) with a trailing slash, is now fully permitted, although described as a transitional feature. Judging from the fact that most new sites still use a transitional doctype we can safely assume that there is nothing stopping us from using an XHTML-like syntax even in HTML 5. I will proceed to argue that it often even is a very good choice.

polyglot documents

Pages using such syntax have even got a recently popularized name: polyglot documents. Let us consider a few features a polyglot document will lack, being sent as false XHTML:

  • No namespace support, but HTML 5 will (probably) special case SVG and MathML, so the most sought after compound documents will still be possible to author.
  • No draconian errors. A feature most developers won't miss at all.
  • XML parsers that rely on the MIME-declaration will fail or refuse the document. There should be easy workarounds for that.

The list can be expanded. I just want to illustrate the fact that in the near future, any benefits of using XHTML syntax will only to small degree be related to XML technical features. Indeed, when HTML 5 lib has become widely available and integrated with all server side scripting languages, we are promised that all of today's XML-server side tools, will work equally well for non-polyglot HTML documents.

The continued benefit 1: XHTML syntax works like a coding convention

Every major project that involves more than one programmer will soon run into the need of following agreed upon standards for things like indentation, placement of braces, usage (or non-usage) of a space between arguments in function calls and definitions, etc. A programmer that does not know or care about this will quickly see his contributions be rejected and is probably considered non-employable.

Douglas Crockford has introduced coding conventions for JavaScript to many and his JSLint tool has options that will ensure that you follow them. HTML Tidy has options to clean up code, but other than that I know of no common code convention for HTML. I know that for many of my friends the beauty of XHTML has been the clean syntax. For reasons like the following:

  • Enforcing lower case element and attribute names are easier on the eye than code that SHOUT.
  • Enforcing citation marks around attribute values makes errors easier to avoid or spot.
  • Explicit closing of elements like li, tr, th, td and p, also make code easier to read. No guessing the intention (was the implicit close intended or just sloppiness?) makes it easier to work with other peoples code, or even code that I've written myself a while ago.

Let me elaborate that second point. One particular nasty problem occurs when attribute values are generated using server side scripts. Let's say that for a few iterations in an applications life a particular value is always a single word, like in "login". Suddenly another developer (or you) decide that it is better to use two words, like "login name". And since the code that generates this value might be miles apart, like in another file and module, from the template that outputs the actual HTML, one can not take for granted that such a change would not break anything. In a sentence: Quoting attribute values makes code more robust!

Counterargument: You can do that equally well in regular HTML

The primaryu counterargument usually sounds like this: But you don't need XHTML syntax. Nothing is topping you from using lower case tag names and attributes or the optional closing tags in regular HTML, if you wish. True. But nothing is enforcing it either! And there is no tool available for testing it, at least none that I know of.

Neither does this counterargument apply too all aspects of my second argument.

The continued benefit 2: XHTML syntax is good for beginners!

A few years ago Lachlan Hunt wrote that XHTML is too hard for beginners. There is basically two things that make me take a stance that is exactly opposite of his. The first is that he is talking about true XHTML, I am talking about false. The second would be that my main job for almost a decade has been to teach complete newbies about web development. I would not presume to know even half of what he knows about the minute details of markup languages. I dare say, however, that I know much more about teaching this stuff to students.

Coding conventions should be taught from day one!

Here is a rule for all teachers of all things coding. Demand that students should use strict coding conventions from day one. Do not think that it can be introduced at a later stage. Sloppy habits are formed from day one, and are much harder to get rid of once they have formed. Often when I look over the shoulder of a student, and see ghastly looking code, the student will say that it will be fixed later. Judging from nearly a decade of experience I know that it will not happen!

Bad habits get picked up from day one. They should therefore be punished from day one. Requiring XHTML syntax is one way to enforce such practice.

XHTML is the more pedagogic syntax

Requiring students to close void elements is a very effective way of teaching them what elements are indeed void. In the days when we use named anchors for intra-page navigation (as opposed to setting the id attribute on any element) I had students that forgot, or lazily omitted the closing tag. Their pages worked just fine. The only downside was a more complex DOM and that was not discernible for their pages. In fact, some of them believed that such an anchor was a void element. It even took a while for me to grasp that it was not. XHTML helped me understanding that, and I've seen it help other people come to grips with similar issues.

Explicitly closing elements helps making students understand the concept of semantics. You do not insert an li just to get a bullet point, all things between the starting and ending tag is a list item. You do not insert a p-tag to get some space between your lines. All text between the starting and the ending tag is a paragraph. Etc. Being forced to constantly ask oneself where something should start and where it should end is a good for learning.

I also would like to add, that requiring XHTML is good for the mental health of me as a teacher, since a lot of errors will be caught by the students themselves during validation, and their code will be easier to read for me.

The true dowsides of false XHTML

Nothing in life is so rosy as to have no negative downsides. With every medicine has its side effects. The two most immediate ones for newbies both involve scripting:

Tag names are sometimes uppercased in the DOM

Such things happen when an organization badly applies the biblical principle of the left hand not knowing what the right hand is doing. However, this confusion will exist, no matter which syntax you chose. Using HTML syntax with all uppercase element names is not common practice and it won't be long until the principle has to be explained to a student anyway.

Technically redundant closing tags will cause un-intuitive text nodes to appear in the DOM

Consider this code:

<ul>
  <li>foo</li>
  <li>bar</li>
</ul>

How many child nodes to the ul-element are there in the DOM? To a newbie (and Internet Explorer) it looks like 2. To the trained eye it is 5. But once again new technology comes to the rescue. By introducing new DOM-walking APIs we can (in the future) ignore those white-space only text nodes, in a cross browser consistent manner, using native API-calls.

Note that the first white-space only redundant text node would still be left, even if we had omitted the closing tags. And lets say for a moment that a student had authored a script that relied upon there being no closing tags. How confused would he/she not be when it suddenly stopped working because someone suddenly used closing tags? How bristle would such code not be in real use?

The future

Maybe there are some technical benefits of XHTML as well, but I hope to have shown that even without them, the syntax has clear benefits — enough to tell my students that they should use it, either as XHTML 1.0 strict or as HTML 5 polyglot. So where do I want to go from here? This is my wishlist for the future:

  1. The (X)HTML 5 spec should be strictly serialization and syntax neutral. XHTML syntax is not only something that should be allowed for transitional reasons.
  2. I would love to have a (X)HTML coding convention tool, that could check for even more details than the current validator does. Things like indentation, or allowing shortened attributes for boolean attributes, while enforcing citation marks for all non-bolean ones, ought to be testable. Such a tool might even make me think that there can arise even better alternatives than polyglot documents.

Monday, July 13, 2009

No backwards compatibility = XHTML 2 was doomed to failure

XHTML 2 is the Itanium of web technologies. You remember Intel and HP celebrating the Itanium architecture as the new super-duper technology, that should leave all RISC-based competitors in the dust. VLIW (re-branded as EPIC) was touted as a disruptive innovation. The future was Itanium.

But it was not! Forget the marketing speak from Intel and its only Itanium customer worthy of being mentioned, HP. Itanium has flopped. Yes, other RISC architectures, are struggling. MIPS no longer power high end servers from Silicon Graphics. SPARC is loosing market share. Only IBM Power PC seems to be holding its ground in the server space. But the x86 architecture, that was supposed to die, is reigning more dominantly than ever.

Backwards compatibility is everything

Being backwards compatible is not only a nice feature. It is a prerequisite that simply seems non negotiable. Let's look at a few successful products to get an idea.

Windows 95 and DOS-based games

Before Windows 95 all high end games were run from the DOS-prompt. Windows 3.x was only a nuisance for game developers. In order to achieve the highest possible speeds they often tweaked the hardware interaction in every possible way. Getting these games to run under Windows 95 proved a challenge, to say the least. Microsoft solved this by special-casing game after game. The operating system would recognize a particular piece of software, know that it required special handling and adjust accordingly. Even in ways that broke protocol.

Punch cards

When were punch cards invented? 1725. When did they become a big success? 1890. When did they become surpassed by other technologies. In the early 1960's. When did IBM drop support for punch cards from their operating systems? Not for another 30 years. I would not even be surprised if it was possible to attach a punch card reader to a brand new z-series computer today, and actually have it work.

XHTML 2 was Dead Pre Arrival

It did not die as a markup language for the web. It never lived. The day the decisions was made not to be backwards compatible, it was doomed. It never really mattered that it had every conceivable shiny new feature. Technical merits are simply not enough. Therefore it simply does not matter how much you shout about them, or how much you disdain the fact that HTML 5, due to its legacy, is awful and badly designed.

Yes, I use PHP too, and no matter how much one shouts the relative technical merits of Ruby or Python, PHP seems not to grow weaker. Ugliness just is not that big a factor. A strong user base, re-use of code and know-how, ability to find advice and support, such things matter. Sociology always trump technology.

The future for XHTML 2

I have friends who prefer XHTML 2 to DocBook, for data storage on the server. Reading Steve Pembertons thoughts about the future, he seems to believe that is a viable niche and that it can make a comeback that way. And why not, in a controlled environment the improved semantics of XHTML 2 over legacy HTML may provide significant benefits. Pushing XHTML 2 as a progressive enhancement, server side, might work.

Encouraged by none other than Ian Hickson himself XHTML 2 will continue to be developed in a working group outside of the W3C. Can it make a comeback? Once upon a time the W3C decided to axe HTML. Many developers, myself included, thought it was the end of HTML. I was wrong. I therefore will not say, good bye XHTML 2, but a revoir.

Sunday, June 28, 2009

Do not put experimental features last in your CSS

Today's blog post will be short one. I have lately seen code like this on more than one occasion:

#foo { 
border-radius : 10px; 
-moz-border-radius : 10px; /* Mozilla */
-webkit-border-radius : 10px; /* Webkit */
}

What is the problem?

Right now only one line will have an effect. In Gecko-based browsers, like Firefox, the one starting with -moz-, in recent Webkit based browsers, like Safari and Chrome, the one starting with -webkit-, as indicated in the comments. These are the two current experimental implementations of the coming CSS 3 border radius property.

Hopefully in the near future the specification will thanks to these two implementations reach a level of maturity, where browsers may start to implement it in a non-experimental version. If so one thing is to be expected. The non-experimental implementation will most likely differ (somewhat) from the experimental one! And as a developer you will most probably want the final version to be the one that browsers actually use. And when two rules affect the same property like this (equal specificity, equally placed in the cascade), the last one will override the first one. Therefore you should put things in this order:

#foo { 
-moz-border-radius : 10px; /* Mozilla */
-webkit-border-radius : 10px; /* Webkit */
border-radius : 10px; 
}

Why is this better?

During a transition phase, lasting at least a few years, Webkit and Gecko can be expected to support both implementations. There are sites that use the experimental versions only and in order to give them a grace period, dropping support as soon as the final version is implemented is not an option. Historically Mozilla has let such grace periods last for 2-4 versions of Firefox.

So this is the bottom line. Put experimental features first, standard features last. That will ensure a better forward compatibility.