iPhone xhtml Javascript Development Woes

The iPhone has been great for mobile, it’s given a full browser to the mobile world. Except for one thing, it’s Safari, which can be good and bad. It’s good for example if you’re developing an app for iPhone, you have one browser to test and develop against. It’s bad because it’s Safari, not known to be the best of browsers.

At AdMob, I’m responsible for developing the javascript ad code for our iPhone specific code. Recently we’ve been experiencing odd behavior on sites where the ad code would simply not run. We finally narrowed it down to the fact that sites were setting content type as application/xhtml+xml. When Safari is in this mode it doesn’t like you doing such things as document.createElement(‘div’) or eL.innerHTML = ‘<div>text<div>’ or even eL.innerHTML = ‘text’; all of which are normal dhtml techniques.

Instead it expects you to use document.createElementNS and document.createTextNode which are the proper way to add XHTML elements. So I ended up having to rewrite our entire iPhone javascript code and a simple nifty utility function. 🙂

  var createElement = function(type, props, styles) {
    var d = document.createElementNS('http://www.w3.org/1999/xhtml', 'html:' + type);

    for(var i in props)
      d[i] = props[i];

    for(var i in styles)
      d.style[i] = styles[i];

    return d;

  // usage
  eL.appendChild(createElement('div', { id : 'divId' },
        { float : 'left', width : 100px' }));