Friday, October 29, 2010

Jangaron 0.71: fix for IE9 beta

Another new browser version needs another patch.
This time, it's IE9 beta: alas, it became too standards-compliant! Thus, a typical crude workaround needed for IE6/7/8 did not work anymore. I fixed it, so you can now enjoy Jangaron in Internet Explorer 9 (beta)! It's fast and it's fun!

Evaluation
In IE < 9, you will run into problems when trying to dynamically create an input field by code like this:
  var input = document.createElement("input");
  input.setAttribute("type", "radio");
Old IEs refuse to interpret the type, also if you set it as a JavaScript attribute. Thus, you are forced to use a proprietary, IE-specific API extension that allows to hand in HTML fragments instead of the element name:
// only works in IE < 9:
  var input = document.createElement("<input type='radio'>");
Unfortunately, the usual way to do feature detection instead of browser detection does not apply here, since the function createElement() is defined in any browser, only old IEs provide additional semantics. So I did browser detection (shame on me), which of course failed when IE 9 (note: only in IE 9 mode, not in any backwards-compatibility mode!) became standards-compliant.
The only way out was to use the anti-pattern programming by exceptions and simply try the extended API and catch the error for standards-compliant browsers. To avoid recurring runtime penalty, I only do this once and store the result in a feature flag:
  var SUPPORTS_CREATE_ELEMENT_WITH_ATTRIBUTES = function() {
    try {
      window.document.createElement("<input type='text'>");
      return true;
    } catch (e) {
      return false;
    }
  }();
Instead of SUPPORTS_... I should maybe call that flag REQUIRES_..., since I do not use this feature because it is supported, but because the way the standard suggests does not work in old IEs.