My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Monday, August 03, 2009

A JavaScript WorkerLocation

This is a quick post (I am going to write another one) about a pure JavaScript implementation of the WorkerLocation W3C Draft Interface.

Why A WorkerLocation


I've instantly started to interact with Cartagen guys, via Ajaxian, as I think that is one of the most interesting canvas related project I've ever seen so far (I like Bespin idea but I do like more Notepad++ :P )
Since after a first and quick read about the project I proposed Web Workers as possible solution for stressful computations, Jeffrey Warren put on the table the fact that Web Workers are not cross browser yet (Internet Explorer 8 anybody?).
Being a developer whose aim is to solve problems, I started to analyze Web Workers specs in order to re-create a cross browser implementation able to let us develop following new standards and bringing them somehow in those browsers where these standards are not standard yet and gosh knows where they will be (Internet Explorer 9 anybody?). Something Google did before with ex-canvas project: when a browser is behind it cannot block everybody else (it should NOT, at least).
I am not sure how possible/good will be my implementation and it will take time, probably too much to propose it to Cartagen guys but right now I have created a cross browser WorkerLocation which is simple and fast enough to be used in any other project.

The WorkerLocation Code



function WorkerLocation(url){
// WebReflection proposal
var m = /^([^:]+):\/\/([^\/]*)([^\?#]+)(\?([^#]*))?(#(.*))?$/.exec(this.href = "" + url);
if(m === null)
throw new Error("Invalid URL");
this.protocol = m[1] + ":";
this.host = m[2] || "";
this.pathname = m[3] || "";
this.search = m[5] ? m[4] : "";
this.hash = m[7] ? m[6] : "";
m = this.host.split(":");
this.hostname = m[0];
this.port = m[1] || "";
};

You can easily compare the WorkerLocation reliability directly in a loop like this one:

var o = new WorkerLocation(location);
for(var k in o)
alert(k + "\n" + o[k] + "\n" + location[k]);

After several tests, I can say that results are always exactly the same of a native location object.

What's WorkerLocation For


Well, runtime script inclusion a la JSONP or just to load dynamically our library is a common practice and moreover, an URL decomposition attributes could be always useful in different situations, with script sources itself, to load other files, to check a link, etc etc ... enjoy ;)

No comments: