04.25.05
Into the javascript future
Ten Good Practices for Writing JavaScript in 2005 is a pretty good article talking about some of the better practices for javascript development with the current state of the web. Lots of good links out to other pages that I will be reading for a bit.
My Biggest disapointment is that innerHTML is going away with XHTML strict since it allows for the creation of invalid XML. I don’t know about everyone else, but I agree with one of the commenters from the discussion on quirksmode: if it was invalid then throw an error or something but allow the use of this for valid XML.
We generate HTML fragments on the server that are requested and added to the page asynchronously. This will mean that we either have to come up with a representation of Html in javascript so that we can send fragments or we have to parse the html input to add the nodes one at a time… or some crack with ranges (see the quirksmode discussion).
The other day we were playing around with how to represent HTML trees in Javascript. I was thinking about the node function.
var a,n = document.createElement(name);
var i;
for(i in attribs)
if(i == “CssClass”)
n.className = attribs[i];
else
n.setAttribute(i, attribs[i]);
//deal with the rest of the arguments which are children
for(i = 2; i < arguments.length; i++) {
a = arguments[i];
if(typeof(a) == “string”) {
n.innerHTML += a;
}
else
n.appendChild(a);
}
return n;
}
Which allows you to represent a mini HTML tree like so:
node(”h1″, null, “Dynamic”),
node(”div”, {CssClass:”jimmy”, style:”height=200px; background-color:green; “},
node(”div”, {CssClass: “jack”, style: “background-color:blue; height=100px;”}, “foo”)));
You pass in a tagname, a object that represents all of the attributes, and then the remainder of the arguments are that nodes children. This has given me a better appreciation of lisp syntax: keeping track of where commas should go as this Javascript tree grows becomes a bit clumsy.