Conditionally loading xui.js for Webkit, Blackberry or IE

10 Mar

by DannyT

My latest theme update led to my ditching jQuery in favour of a lighter alternative in the form of xui.js. From the xui site:

“a super micro tiny dom library for authoring html5 mobile web applications.

// a trivial example
x$('#btn').click( function (e) {
    x$('#msg').html('Thanks for your submission!');
})

features

  • clean, familiar, chaining syntax.
  • super tiny 10.4kb footprint (4.2kb gzipped).
  • only library with targeted builds for webkit, ie mobile, and blackberry.
  • mit licensed.”

Xui was spawned from the PhoneGap project so comes from some bright folk like Brian LeRoux of Adobe (PhoneGap), Mobile Minute podcast, wtfjs and various other useful webby places.

I also looked at Zepto.js which seems to have similar goals and some great momentum but as that explicitly does not support IE and I’m currently playing with Windows Phone 7 I didn’t really want to exclude myself and the rest of the WP7 minority contingent :P .

Whilst Xui supports Webkit, Blackberry and IE it doesn’t do so at the expense of additional file size. This was one of the things that appealed to me. However, I did need to figure out how to conditionally serve up the appropriate build of the library depending on the target device. I’m not 100% sold on the approach but for now I’m simply applying a conditional based on user agent and loading the library at the bottom of html document like so:

  <script>
    var ua = navigator.userAgent.toLowerCase();
    // uses wordpress function to get theme js dir where all js libs live...
    var xuiJs='<?php bloginfo( "template_url" ); ?>/js/';
 
    // append appropriate xui file based on user agent
    if (ua.indexOf("blackberry") >= 0)
    {
      xuiJs+='xui-bb.min.js';
    }
    else if (ua.indexOf("msie") >= 0)
    {
      xuiJs+='xui-ie.min.js';
    }
    else
    {
      xuiJs+='xui.min.js';
    }
    // dynamically add script tag to page
    document.write('<script src="', xuiJs, '" type="text/JavaScript"><\/script>');
  </script>

I did consider doing this on the server-side but wanted a more portable solution rather than being dependant on php which this blog runs on so went with the pure js approach for now. As the js on the site is used for progressive enhancement, if there is a problem it shouldn’t cause any major issues but I’ve tested on iOS, Android and WP7 and all seems to work well.

Like I said I’m sure this isn’t the absolute best solution so feel free to tweet me any advice/abuse/thoughts on the approach @dannyt.