Google Voice Click-to-call Widget

1 comments

I'll keep this short. I was lucky enough to get in on the Google Voice closed beta (back when it was Grand Central). It offers a free click-to-call widget that you can embed in your web pages. But it didn't offer quite enough "pizzaz" for my taste, so I enhanced it a bit using some Javascript. I'm making the code freely available. (It should be an interesting read.)

It works in IE 6 through 8 as well as Firefox 3 and Safari 3. I didn't test it in anything else. To see it in action, use one of the aforementioned browsers and go to http://techhead.biz.

Feel free to use it, improve it, etc. As always, a little credit here would be appreciated. If you do use it, please leave a comment here and drop a link so I can find you.

DOMContentLoaded and ondocumentready and onreadystatechange! Oh my!

0 comments

How do you determine when your document is ready to be manipulated by the javascript in your web application? In the course of a recent project, I discovered that the answer is perhaps not so simple as the question. In fact, the conclusion I've come to is that "it depends".

The most elegant solution I've come across (in my opinion) is the DOMContentLoaded event. This event has been hidden in Mozilla browsers since I don't know when (???) but has now been adopted in recent versions of WebKit and Opera as well. As the name suggests, this event fires when the document tree (DOM) is completely loaded. This may fire before images and other external objects are loaded. The only problem is that IE 6, 7 and 8 don't support it, so there goes the market share. The rest of this article is about various "hacks" which attempt to emulate this behavior in IE.

The current most popular workaround (and newest I believe) is a "hack" discovered by Diego Perini. It is based on the ondocumentready event that is available only to Behaviors in IE. Diego discovered a paragraph in an MSDN document and ran with it.

A few methods, such as doScroll, require the primary document to be completely loaded. If these methods are part of an initialization function, they should be handled when the ondocumentready event fires.

Taking the reverse of this statement, Diego tried polling doScroll until there were no more errors as a means to achieve a "poor man's" ondocumentready. And guess what? It works! ...Sort of. If the loading document's window is not top level (ie. if in an iframe), doScroll never errors and the hack falls apart.

// Should return true only if the document is ready, false otherwise
// Works unless in an IFRAME
function documentready() {
  try {
    window.doScroll('top');
    return true;
  } catch (e) {
    return false;
  }
}

function init() {
}

// Poll until documentready
(function() {
  if (documentready()) return init();
  setTimeout(arguments.callee, 0);
})();

Another popular method of DOMContentLoaded emulation in IE is the deferred SCRIPT method made popular by Dean Edwards.

function firedomload() {
}

// A deferred, external script is executed after the DOM is available in IE.
// I know of no formal specification for this behavior.
// However, it appears consistent across IE 6 through 8.
// MUST use a document.write to emit the SCRIPT (if being placed dynamically)
//   or readyState never reaches 'complete'.
//   (I don't know why, but that's just the way it is.)
document.write('<' + 'SCRIPT src="//:" defer><' + '/SCRIPT>');
var script = document.documentElement.lastChild.lastChild;
script.onreadystatechange = function() {
  if (this.readyState == 'complete') {
    this.onreadystatechange = null;
    this.parentNode.removeChild(this);
    firedomload();
  }
};

The problem with this method is, of course, is that it requires a call to document.write which will obliterate the current document if called too late.

Dean also shows us how to take advantage of the ondocumentready event directly, but this method requires an external HTC Behavior file, making it less friendly for inclusion within libraries.

Lastly is the most obvious option. Place a script after all of the content in the BODY of your document and use it to bootstrap the initialization calls.

<html>
<head>
<script type="text/javascript">
if (typeof ondomload == 'undefined') ondomload = [];
ondomload.push(function() {
  alert('This will execute on DOM load');
});
</script>
</head>
<body>
... some content ...
<script src="firedomload.js"></script>
</body>
</html>

And the firedomload.js script looks like this...

/**
 * This SCRIPT should be placed just before the close of the BODY element
 * in your (X)HTML document. It may be deferred.
 *
 * Scripts that take advantage of 'ondomload' may come before or after
 * this SCRIPT and may be either deferred or not deferred.
 *
 * USAGE:
 * if (typeof ondomload == 'undefined') ondomload = [];
 * ondomload.push(function() {
 *   alert('This will execute on DOM load');
 * });
 */
if (typeof ondomload == 'undefined') {
  ondomload = {};
} else {
  while (ondomload.length)
    setTimeout(ondomload.shift(), 0);
}
ondomload.push = function(cb) { return cb() };

In summary, each method has its pros and cons. Even the library authors can't agree on what is best. At the time of this writing, jQuery uses the doScroll method and Prototype uses the deferred SCRIPT method. I've written a small function using the deferred SCRIPT method. You can find it here. The source code for the tests is also available here. And there is a live test here.

What you use may depend on your needs.

Running IE6, IE7 and IE8 on your Mac (reloaded)

1 comments

The original article is here: http://blog.mozmonkey.com/2008/vpc-ie6-ie7-ie8-on-mac-os-x/

I came across the above article a while ago when looking for a good way to test my web sites in Internet Explorer without having to resort to using a PC. Microsoft releases Virtual PC images of Windows containing various versions of the Internet Explorer web browser. These expire and are re-released periodically. At the time of this writing, they are about to expire again. I do hope that Microsoft will continue this valuable service. (It's the least they can do.) You can download the images here: http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF

If you are using Windows, then you may download the free Virtual PC from Microsoft. Otherwise, download the free, open source VirtualBox. At the time of the article noted above, it was necessary to first convert the Virtual PC images before they could be used on VirtualBox. This is no longer the case.

The Virtual PC images available from Microsoft come packed in self-expanding archive files. This is a small problem if on a Mac. You cannot run the self expander, but I find that the free Stuffit Expander works fine to extract the image file.

Once you set up your virtual machine, Windows will boot, show you the EULA and attempt (and fail) to install a bunch of "new hardware". Just skip past all of this and then choose "Devices -> Install Guest Additions..." from the menu bar. This allows better integration with your system. It also makes folder sharing with your Mac possible.

Of all those hardware installation dialogs you clicked past earlier, one of them was to install a network device. Without this, you can't access the internet. At the time of this writing, VirtualBox emulates an AMD PCnet-FAST III NIC by default. You will need to download the driver for it here. Then you'll need to setup a shared folder and put the driver in it so that you may install the driver from Windows.

If you're a more visual person, just watch the video here (or inline below).

Google App Engine is available for Java developers

0 comments

I'm sure that you've heard the news by now, but I couldn't let it pass without a comment. Hooray!

I am a Java developer. That is to say, Java is the language I have done most of my development in over the past 10 years. But my interest lately has been less in Java actual and more in the JVM and all the Groovy new languages you can get to run on it.

That's why I'm particularly excited that the App Engine will support such alternate languages. I was lucky enough be get in on the developer preview, so you can expect to see me posting more on this topic in the new few weeks.

Stay tuned.

Prototype-based programming in Javascript (part 2)

1 comments

This is part 2 of the subject. For a primer on prototype-based inheritance in Javascript, see the previous article.

Javascript is a prototype-based language, but sometimes it pretends not to be. Constructors, types, the new and instanceof operators -- these are all an additional layer built on top of the core model. And they make it a little difficult to tell what is really going on... So we're going to take them out of the picture. Here's a summary of the last article in SpiderMonkey Javascript.

// Prototype inheritance
A = { foo: true }; // new A
B = {}; // new B
B.__proto__ = A; // If a property is not found in B, look in A
alert(B.foo); // true
B.foo = false;
alert(A.foo); // still true

// the 'new' operator can be reproduced in SpiderMonkey Javascript
function nuevo (constructor) {
  var newObject = {}; // new object with its own properties
  newObject.constructor = constructor; // this is the new object 'type'
  newObject.__proto__ = constructor.prototype; // desired prototype obtained here
  // call the constructor on the newly created object
  constructor.apply(newObject, Array.prototype.slice.call(arguments, 1));
  return newObject;
}

Ok, so now that you know how prototype inheritance works, lets make it a little easier to use. There are already many good libraries that make "classical" or class-based inheritance easier in Javascript. (My favorite is the simple one provided by John Resig on his blog.) But I'm not yet aware (I'm sure you'll help me here) of any that make prototype-based programming simpler. Douglas Crockford, Javascript god, has a simple function posted on his site. We'll start with that.

Object.create = function (o) {
  function F() {}
  F.prototype = o;
  return new F();
};

You should know by now what this is doing. The constructor function F is necessary because there is no universal way to set a prototype chain directly, other than specifying it on a constructor. The type F is a throwaway. You don't need it anymore. You won't be using the new operator, and the instanceof operator makes no sense for pure prototype-based programming anyway. (Instead, you would use the Object.prototype.isPrototypeOf method found on every object.)

Using Crockford's function, our first code example now looks like this.

// Prototype inheritance
A = { foo: true }; // new A
B = Object.create(A); // new B

Pretty simple, and it's almost all you need. But I find that in practice, some additional features are useful. Here's a first iteration of my version.

var Proto = {

  __proto__: Object.prototype,

  clone: function(init) {
    var Clone = function(init) {
      this.__proto__ = Clone.prototype;
      this.constructor = Clone;
      if (init) this.assign(init);
    }
    Clone.prototype = this;
    return new Clone(init);
  },
  
  assign: function(props) {
    for (var key in props) {
      var value = props[key];
      if (this[key] != value)
        this[key] = value;
    }
    return this;
  }
  
}

There's not a whole lot of difference between my own and Crockford's here besides naming, but there are some significant things going on. For one, Crockford attaches his function as a property of the Object constructor. This makes perfect sense, unless you consider that the whole reason he scrapped his first iteration (in which the function was simply named object) was that "globals are clearly problematic". But you actually have all the same problems (namespace issues, etc) here.

On another of his iterations, he attached the method begetObject to the Object.prototype. The problem here is that adding anything to Object.prototype will cause it to be inherited by every single object in the global namespace, whether or not it's actually part of your program. I made a compromise and added my clone method to the prototype of the Proto object. So only objects which inherit from Proto will be affected. Of course, there are still no guarantees that other code in the global namespace will not interact with the name Proto, but you can name this whatever you will (eg. biz$techhead$Proto if you like).

Another thing you'll notice about my "improvements" is that I explicitly set the __proto__ property of the new object. The __proto__ property really only means anything in Mozilla's Javascript, and I simply set it to what it was already. The reason I set it is because it is a useful relationship to preserve, and now I have read access to it even in Internet Explorer. I also set the constructor property for the sake of correctness.

Lastly, you'll notice that I added an optional initializer to assign properties to the newly constructed object. This is merely a shortcut.

But I'm not quite done. For one, it is useful on occasion, even when using prototypes, to be able to call a method on a super prototype. A naive attempt and its correction is shown below.

A a = Proto.clone({
  create: function(name) { return this.clone({ name: name }) }
});

B b = A.clone({
  create: function(name, gender) {
    // this may look right at first glance
    // but will quite often end up in an endless loop
    // see if you can figure out why
    // var o = this.__proto__.create.call(this, name);
    // instead, this is correct
    var o = A.create.call(this, name);
    o.gender = gender;
    return o;
  }
});

But I don't really like having to refer to the super prototype by name. If I decide to change the name from A to something else, I've got to change B also. Not a disaster but it is still annoying. So I provided a way to access the super prototype through a generic name.

A bigger issue I've found is that sometimes a prototype needs to be able to control exactly how it is "copied". Sure, it could override the clone method each time, but that is a lot of extra work for a common task, so I set up an event instead. Behold the next iteration.

var Proto = {

  __proto__: Object.prototype,

  clone: function(init) {
    var Clone = function(init) {
      this.__proto__ = Clone.prototype;
      this.constructor = Clone;
      this.onclone();
      if (init) init.call(this, this.__proto__);
    }
    Clone.prototype = this;
    return new Clone(init);
  },
  
  onclone: function() {}
  
}

Notice that on my last iteration, you could provide an object to the clone method and it would copy its properties onto the new object. In this iteration, you may provide an initialization function (much like a constructor) to set up the new object. This provides a couple of new advantages. See the example below.

Animal = Proto.clone(function() {
  this.eat = function(food) {}
  this.sleep = function() {}
  this.poop = function() {}
  this.breed = function(animal) {}
});

Human = Animal.clone(function(_super) {
  var ate = [];  // now I get a new private scope
  this.eat = function(betterfood) {
    _super.eat.call(this, betterfood); // can use _super instead of Animal
    // do something else
    ate.push(betterfood);
    // sorry about the lame example
  }
});

So, with the latest and greatest iteration, I get access to a _super keyword and the ability to easily add private members to an object. But wait! The private member ate is now shared by all humankind. This is probably not what the programmer had in mind. Instead, this probably was...

Human = Animal.clone(function(_super) {
  var init = function() {
    var ate = [];  // now I get a new private scope
    this.eat = function(betterfood) {
      _super.eat.call(this, betterfood);
      ate.push(betterfood);
    };
  };
  this.onclone = function() {
    _super.onclone.call(this);
    init();
  };
  init();
});

Now each Human keeps his own menu to himself. But that's a lot of extra typing for something that should be simple, so I'll add one last bit of magic...

/**
 * The prototype of all objects in this small
 * prototype framework.
 */
var biz$techhead$Proto = {

  __proto__: Object.prototype,

  /**
   * Clone this object and (optionally) invoke an initializer.
   * Should NOT be overriden.
   * Override 'onclone' instead.
   */
  clone: function(init) {
    var Clone = function(init) {
      this.__proto__ = Clone.prototype;
      this.constructor = Clone;
      this.onclone();
      if (init) {
        if (init instanceof Function)
          this.init(init);
        else
          this.assign(init);
      }
    }
    Clone.prototype = this;
    return new Clone(init);
  },
  
  /**
   * This event fires on the new child of this object
   * whenever 'clone' is called.
   * It is analagous to a constructor.
   */
  onclone: function() {},
  
  /**
   * Invokes an initializer function on this object.
   * It supplies this object's super prototype as the
   * first argument, and provides an optional second
   * argument to those initializers that declare
   * two or more parameters. The second argument is a
   * function that will install the initializer 'onclone'
   * when invoked.
   */
  init: function(init) {
    var _this = this,
        _super = this.__proto__;
    if (init.length > 1) {
      init.call(this, _super,
        function() {
          var hasonclone = _this.hasOwnProperty('onclone'),
              onclone = _this.onclone;
          _this.onclone = function() {
            var _this = this;
            var f = hasonclone ?
              function() { onclone.call(_this) } :
              function() { _super.onclone.call(_this) };
            init.call(this, _super, f);
          };
        });
    } else {
      init.call(this, _super);
    }
  },

  /**
   * Shallow copies the given properties onto this object,
   * excluding those already owned by this object
   * (eg. those inherited through Object.prototype).
   */
  assign: function(props) {
    for (var key in props) {
      var value = props[key];
      if (this[key] != value)
        this[key] = value;
    }
    return this;
  }
  
}

I just added a bit of sugar that allows you to set the 'onclone' event handler to the initializer in one step. Now the following is possible.

Human = Animal.clone(function(_super, install) {

  install(); // This initializer method will run 'onclone' also.
             // install() will automagically be replaced with a call
             // to _super.onclone when called from the 'onclone' event
  var ate = [];
  this.eat = function(betterfood) {
    _super.eat.call(this, betterfood);
    ate.push(betterfood);
  }
});

You can find the "finished" framework here. I hope you enjoyed this journey as much as I did. Please comment, and let me know your thoughts on prototype-based program design.

Prototype-based programming in Javascript

0 comments

You may have heard that Javascript is a prototype-based programming language, but chances are that you've never used it that way -- not really. Maybe that's because prototype-based programming is kind of... well... different.

Now, I must admit that I think prototype-based programming makes sense to me, but I haven't ever actually used it in a project. (Until now.) In fact, you might be hard pressed to find any projects in which this programming model is being used, and I am curious to know why. Is it because it is awkward, or is it a hidden gem?

My interest is both academic and practical, in the sense that I love to explore programming language methodologies but I also actually write code. It seems, other than Javascript, the prototype model exists largely in academia. You'll hear a lot about Self, a Smalltalk derivative, but I am unaware of any projects actually written in Self. My favorite example of a prototype-based programming language is Io -- in which I have never written a single line of code. But its documentation helps to illustrate the point. I will translate one such example into how Javascript would look if it were more straightforwardly prototypal (and then we'll work on making it so).

Account = Object.clone();
Account.balance = 0;
Account.deposit = function(amount) {
  this.balance += amount;
}

account = Account.clone();
account.deposit(10.00);
alert(account.balance);

In the above example, notice that there are no classes nor constructors. Account is an object. It has a balance. You can even call the deposit method to change that balance. But the Account object was not likely created to be used directly. Instead it is intended to be more of a rubber stamp, a model which can be cloned.

And under the hood, Javascript works this way too. The confusion comes largely from the adhoc type system that is built on top of the prototype model. Take away the new and instanceof operators and using prototype inheritance in Javascript might be more straightforward. (I am not suggesting this, however. I love the flexibility that Javascript provides.)

The previous Javascript example does not work, of course. There is no Object.clone() method. But that is essentially what the new operator does. (More on that later.) In SpiderMonkey Javascript (Mozilla's implementation), the above code could be rewritten as:

Account = {
  balance: 0,
  deposit: function(amount) {
    this.balance += amount;
  }
}
Account.__proto__ = Object.prototype; // Object itself is a constructor,
                                      // not an 'instance'

account = {};
account.__proto__ = Account;
account.deposit(10.00);
alert(account.balance);

And this more clearly shows what is actually going on and the relationship between objects in prototype-based models. Account defines two properties, balance and deposit, but it also declares that it inherits properties from Object.prototype by setting Account.__proto__ = Object.prototype. Thus if you attempt to access a property that does not exist for Account, Object.prototype will also be searched. However, it is important to remember that each object has its own properties (or slots). In the above example, setting account.balance = 1000 does not change Account.balance. This is a good thing.

It is worth mentioning also that in some major Javascript implementations (most notably IE), you cannot set an object's prototype chain directly as we did in the prior example. It must be set on object "construction".

Constructors are the adhoc type system of which I spoke earlier. They are nothing more than simple initializer functions, but they also are responsible for setting the prototype chain by way of their prototype property. As always, code speaks louder than words. Below is what the new operator might look like in SpiderMonkey.

function neww (constructor) {
  var newObject = {}; // new object with its own properties
  newObject.constructor = constructor; // this is the new object 'type'
  newObject.__proto__ = constructor.prototype; // desired prototype obtained here
  // call the constructor on the newly created object
  constructor.apply(newObject, Array.prototype.slice.call(arguments, 1));
  return newObject;
}

function FauxAccountClass() {
}
FauxAccountClass.prototype = Account;

account = neww(FauxAccountClass);
// or, same thing...
account = new FauxAccountClass();

alert(account instanceof FauxAccountClass); // will alert 'true'

Please let me know if something is not clear. To summarize, a constructor is simply a function. The prototype property of that function (eg. FauxAccountClass.prototype) decides what the "parent" object of the new object will be. Constructors are the basis of the Javascript type system. However, if you "forget" about constructors and the operators designed to work with them, you still have Javascript ...and an entirely different way of using it. That's where I'm going to take you next. But this article is already quite long, so I'll continue in a follow-up post.

The follow up is now online here: http://devblog.techhead.biz/2009/04/prototype-based-programming-in_04.html

Dynamically load external Javascript in a cross-browser way

0 comments

If you've done any significant Javascript development, I'm sure that you've run into the need to dynamically include an external javascript library. There are many existing libraries that will do this for you quite easily. But what if you are not able to take advantage of such a library? What if that library is precisely the javascript you wish to dynamically load?

Hmm. In that case you can use the following code snippet to bootstrap the process.

function loadScript(src, callback) {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  var loaded = false;
  script.setAttribute('src', src);
  script.onload = script.onreadystatechange = function() {
    if (!loaded && (!this.readyState || this.readyState == 'complete'
                                     || this.readyState == 'loaded') ) {
      loaded = true;
      callback();
      script.onload = script.onreadystatechange = null;
      head.removeChild(script);
    }
  }
  head.appendChild(script);
}

For example, here's how I used it to bootstrap jQuery in a bookmarklet I wrote.

(function() {

function loadScript(src, callback) {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  var loaded = false;
  script.setAttribute('src', src);
  script.onload = script.onreadystatechange = function() {
    if (!loaded && (!this.readyState || this.readyState == 'complete'
                                     || this.readyState == 'loaded') ) {
      loaded = true;
      callback();
      script.onload = script.onreadystatechange = null;
      head.removeChild(script);
    }
  }
  head.appendChild(script);
}

function withJQuery(cb) {
  loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
    function() {
      cb(jQuery.noConflict(true));
    }
  );
}

withJQuery(function($) {
  // do something with jQuery
});

})();

Notice that the above code adds nothing to the global namespace. The code is localized within an anonymous function and jQuery.noConflict(true) is called so that jQuery cleans up after itself and resets the $ and jQuery globals to whatever they were prior to the script being loaded. Nice, but admittedly a lot of bootstrap code.

I've been thinking a lot lately about how a robust javascript packaging system would look. But even then, a nice library wouldn't help a lot here. It would have to be part of the language, and I am not anxious for any additions to the language that have not been very well vetted.

Welcome to the shiny new TECHHEAD Development Blog

0 comments

The other TECHHEAD blog has existed (and been largely neglected) for some time now. However, its core audience has always been the technologically challenged, which made my occasional programming or web-development-related article all the more absurd.

But I've needed an outlet. Programming (and web development in particular) is my passion. It is my intention to share that with you here. But be forwarned; I am not a natural blogger. The necessary regularity and dedication has not yet been developed. I'd rather write code than English. So we'll see what happens. Be sure to subscribe to the feed before you go.