Wednesday

GitHub, Taming document.write and node.js fun

I have a few projects on GitHub now.

The serious project is writeCapture.js. It exists to solve a corner case of the "load some HTML and inject it into the document" pattern. I love this pattern because it's generally the simplest way to combine Ajax with progressive enhancement. The idea is that you load a HTML fragment and just stick it into the document, or replace the old fragment with the new fragment. It degrades easily, and keeps things simple. The only problem is when the HTML you're loading is outside of your control, or can't be changed for some reason. Maybe it's a service provided by a 3rd party. If the HTML contains script tags, and the script tags contain calls to document.write, you're going to have 1 of 2 bad outcomes:
  1. If you just use innerHTML, the scripts probably wont run (at least, not in every browser), so whatever content document.write provides will be missing. That's probably bad.
  2. If you use jQuery.html() or .replaceWith() or any jQuery manipulation method, the scripts will run, and all the content already in the document gets wiped out. Oops.
So this is the part where you realize that you need writeCapture.js. It's open source, well tested, and covers every possible convoluted way that document.write can be slipped into a script: inline, local script file, cross domain and any combination of the 3 (even the script that writes a script tag that includes a script that uses document.write case. Seriously.) You're welcome.

Lastly, I've been having fun with node.js. node can do a lot of things, but using it as a web server/application is the one that appeals to me most, so I wrote a simple web server that streams whatever files are in the current directory. Of course, you can make it do anything you want in response to a HTTP request (or use raw sockets, or whatever) and I'm sure there are a dozen (G)rails like frameworks being written for it as we speak. Enjoy.

2 comments:

Mark Hansen said...

Hi, I was really impressed with the readability of your node.js simple web server, so I forked it on github, added a few features, and I'm using it to run my website! Just wanted to say, thank you.

Mike said...

Love the writeCapture - it solved nearly all of our DART problems on newsweek.com. Locally, it's referred to as the Jesus Script.