Wednesday, 28 January 2009

Streaming Javascript

One of my favourite features of Javascript is the ability to write more source code on the fly. Usually in most languages I've used before in the past, you'd have to write the code, compile it, link it, then run. In Javascript you can write source code which writes source code and runs it ON-THE-FLY.

So for example I could do this in my code.

// Create a new script element
var bamScript = document.createElement( 'script' );

// Fill in the script element with more source code
bamScript.text = 'function bam() { alert("aahh"); }';

// Add our script to the document
document.body.appendChild( bamScript );

// Run our newly added script.

This piece of code, would add in a new script element with a function called bam, which we can run right after it's added to our document. AMAZING!

(Note: A few gotchas I came across. Make sure you use the text parameter and not the innerHTML one. InnerHTML will work fine in Firefox, however in Internet Explorer it'll go boom, and on the iPhone's safari, it'll go boom depending on the complexity of the source code you're writing.)

Since the beginning of iGrapher I've been meaning to use this feature of Javascript, however with the use of gzip, my javascript has been small enough to avoid needed to split the program into separate downloadable components. However, since porting to the iPhone, I've found that it takes a good few seconds to load, so I finally pushed ahead the usage of self-writing source code.

So now in v1.56 iGrapher will load in a small script which dynamically streams in more source code using the XMLHttpRequest object. At the moment the source code is split in two, however I plan on breaking it up into further components so at first the necessary components download first, then the non-essentials (top menu, data spanner, etc.)