remy sharp’s b:log

Tech bits ‘n bobs

jQuery 1.2 introduced JSONP support, but on initial read of the release notes, I wasn’t completely sure what it was - so for anyone else that might want the Dr Seuss explanation.

JSONP is script tag injection, passing the response from the server in to a user specified function

How you can use JSONP

You need to mould both your request and response to handle JSONP - and in doing so, you can have cross domain JSON requests.

Your server will need to return the response as JSON, but also wrap the response in the requested call back, something like this in PHP (hosted on http://myotherserver.com):

$data = getDataAsJSON($_GET['id']);
echo $_GET['jsonp_callback'] . '(' . $data . ');';
// prints: jsonp123({"name" : "Remy", "id" : "10", "blog" : "http://remysharp.com"});

The jQuery script would be:

$.ajax({
  dataType: 'jsonp',
  data: 'id=10',
  jsonp: 'jsonp_callback',
  url: 'http://myotherserver.com/getdata',
  success: function () {
    // do stuff
  },
});

jQuery will change the url to include &jsonp_callback=jsonpmethod - but you can exclude it and it default to just ‘callback’.

Example in the Wild

Twitter’s JavaScript blog plugin works in exactly the same way. You create a function to handle the data from Twitter, and insert a script tag. Once the script is inserted, it calls the function passing the Twitter data as a JSON object.

How it works in jQuery

jQuery attaches a global function to the window object that is called when the script is injected, then the function is removed on completion.

Note that if the request is being made to the same domain, then jQuery will switch it down to a straight Ajax request.

Potential Problems

  1. Security. There’s documents out on the web that can help, but as a cursory check, I would check the referrer in the server side script.
  2. There’s no error handling. The script injection either works, or it doesn’t. If there’s an error from the injection, it’ll hit the page, and short of a window wide error handler (bad, bad, very bad), you need to be sure the return value is valid on the server side.

The FOWA conference ran for two days from the 3rd of Oct. My focus was very much the developer track, though perhaps I’ll visit next year and sit on some of the entrepreneur sessions.

The highlights for me, in no particular order, were:

  • Meeting and chatting to John Resig
  • Steve Souders’ presentation on high performance web sites
  • Patration! and 300 slides
  • Taking Your Application Mobile & real mobile web by Heidi Pollock
  • Diggnation
  • Listening to Matt Mullenweg

New apps/web apps/services I discovered during the event (in order of appearance):

The Best Bits

Frankly the idea of going to a two day event where I knew absolutely no one, coupled with my exceptionally poor networking and small talk skills was a little bit daunting.

However, the sessions were superb. A great effort on Carsonified (formally Carson Systems) part.

Web Site Performance

The first day held the Yahoo presentation on high performance web sites, and although I had inadvertently seen the presentation already - the points Steve Souders ran over really started to drum in to my head - so much so, the first thing I did when I got back to DL was to start putting these in place for the latest project I’m working on.

Mobile Applications

Heidi Pollock ran a session on mobile applications. Her energy was great. Her hostility towards all the variations of mobile browsers was awesome - the mobile platform, and forget the iPhone, it’s a tiny, tiny drop in the ocean, has well over a 100 variations of browser. On top of which, even with the same mobile phone, and same web site, the mobile carrier can still modify the payload causing additional headache to the whole mobile dev. I thought I had problems with IE6 and IE7: phah!

My first, and biggest annoyance from the conference, wasn’t the sessions, but perhaps the attendees - in particular, as each technology was announced, usually the first thing that would spring to mind, or be asked of the speaker was:

When will it be available on mobile?

<rant> Who cares? We don’t have a solid HTML platform on mobile yet. The iPhone is going to support Flash, and soon so will Opera and the Blackberry, but there’s so many other devices out there - and isn’t the main point of mobile web apps that the target audience is so broad? The iPhone and Opera devices sadly aren’t the majority, so if you want the attention of the big audience, forget Gears on the mobile, forget AIR on the mobile - start with HTML on the mobile </rant>

Quick list of mobile bits if you’re interested:

  1. Best screen res to aim for is 176px wide.
  2. Forget standards and forget semantic web if you want to succeed. An <h1> tag is easily, and better replaced by a <b> tag (note: not a <strong> tag - see next point).
  3. Every byte counts. A <b> tag is 10 characters less than a <strong> tag (since you’re closing tags too).
  4. Every character counts - I can’t remember exactly, but it’s something like 20 chars wide by 9 lines deep. If you’re translating - then think very carefully about your wording.
  5. Use xhtml mobile profile 1.0 and not 1.2 - it’s better supported.
  6. Checkout WURFL.
  7. Mobile phone acid test
  8. If I remember correctly, the most popular mobile browser is the Motorola V3

Meeting the Man Behind jQuery

Although John Resig wasn’t there to speak about jQuery is would only be polite to thank him for it.

His talk covered how JavaScript is moving forward, and particularly JavaScript 2, how it will be available in IE, albeit kicking and screaming.

Our conversation spurred me on to Rhino and some server side DOM parsing (which I’ll be posting on separately).

Utility Computing and 300 slides in 30 minutes

In honesty, I hadn’t heard of the chap before, nor had I heard of utility computing - though I certainly knew and employed the technique myself.

The idea that the basic bits of building web sites we redo all the time, and how, for example, FaaS (Frameworks as a Service) allow us to leapfrog that tedious and simple tasks. How products like S3 and EC2 supply the HaaS (Hardware as a Service).

However, all this intellectual and product gumph aside, he also threw himself through 300 slides in a carefully crafted 30 minutes and introduced (::erhem::) us to the word:

Patration: “the freedom and portability to move from one service provider to another without hindrance or boundaries”

Which, silliness aside, is exactly the approach we should be taking when building our web apps. The idea that if you’re using an external platform/provider, there should be some commonality to them to allow you to move without having to rewire your entire solution. You wouldn’t rewire your house just because you moved would you.

Wordpress Founder

Listening to Matt Mullenweg and not only realising that everything he had said made sense, but it was also stuff I knew. This only says that I’ve been doing the right thing, and if he can make a great business (and his own mark out on the web) out of it, then I definitely have it lurking inside me somewhere too. No doubt so do many other people, and I look forward to their competition and being spurred on.

Diggnation, and a 1000 over excited techies

I’ve never seen Diggnation before, so the idea of it being filmed live wasn’t that exciting (particular as I was on my own). The only thing I get excited about is the prospect, and actually having, snowboarding holidays, and perhaps sticking IE one after cracking some bug - aside from that, I’m pretty unimpressed by most things.

The £3 bottle of Becks helped (yep, £3, ouch!), but the biggest thing I was surprised about, and still can’t get my head around, was the some 1,000 (perhaps…) techies, standing, shouting, whooping, and yelling for Diggnation and Kevin Rose. It felt quite wrong!

All that said, I really did laugh out loud and hard at the comedy Alex Albrecht had somehow produced by playing against straight guy Kevin Rose.

Future of Web Apps

Anyone wanting to know what the future holds for web apps: either get yourself some tickets for the next event, or even better: go out and create the future of web apps.

We’re in the midst of a web revolution, and expectations are high, and the competition is even higher. However, there’s still room for the right idea to be bootstrapped and pushed kicking and screaming out of the door ready to take on the World.

Good luck developers, and I’ll see you by the bucket at the end of the rainbow!

FOWA 2007

I’m off to the Future of Web Apps and following on from dConstruct, I have high expectations.

I’ve looked through the line up, and I’m 99% certain that I’ll be spending all my time watching the developer’s floor - some pretty interesting stuff (which I hope to write a few notes up later on in the week).

The sessions that I’m most interested in hearing are:

  • High Performance Websites - Steve Souders (Yahoo!)
  • The Future of Firefox and JavaScript - John Resig (Mozilla Corporation)
  • Comet: Making the Web a 2-Way Medium - Joe Walker (DWR)
  • An Insight to FireEagle - Tom Coates (Yahoo!)

That said, I can say I’m keen to hear all the sessions over the two conference, and no doubt that I’ll be laying my dirty little mitts on all the freebies I can get (and missing my wife those lonely days that I’m away from home)!

There’s also Diggnation being filmed live on the Wednesday, which will be interesting to see - I’m not one of those that go droopy over Kevin Rose, and in honesty it’ll be the first Diggnation I’ll have actually seen.

Then straight after there’s a shin dig (erhem - pardon the pun), which mixed with free booze, sounds like a good way to get over the mid-week hump.

I’m currently working on a project that’s heavily JavaScript driven. One of the key goals of the project is to get the user to click a bright yellow button (I won’t go in to any more detail than that).

The button is perfect, it’s eye catching and when you see it, you just want to click on it. When it’s clicked, it fires the appropriate JavaScript event.

Problem!

However, our success was also our downfall: the button would be clickable before the DOM had completely loaded.

The application wasn’t designed to degrade, mostly because it has a particular targeted audience, so the clicking action screws up the experience if the DOM isn’t finished and all the appropriate click handlers are in place (and yes: I did argue for a degrading system, but that’s entirely another story).

Solution.

The solution is straight forward. You hook a click caching system during the DOM load.

All the links you want to catch an early click event, you add the following:

<a href="#?"
  onclick="return earlyClickHandler.call(this);"
>CLICK ME!</a>

Then the following JavaScript needs to be added as the first block of JavaScript directly after you load jQuery (or your library du jour), in the <head> tag:

function earlyClickHandler() {
  var t = this;
  if (typeof $.isReady == 'boolean' && $.isReady) {
    return true;
  } else if (!t.clicked){
    t.clicked = true;
    // once DOM is loaded, fire this click handler
    $(function () {
      $(t).click();
    });
  }
  return false;
}

The effect is the user can click on the link and it won’t do anything until the DOM is loaded, and once it is loaded, it will fire the click event the user requested.

This example only caches one click event per link (with the t.clicked = true). It is also using jQuery to test if the DOM is ready, and if it is, just pass control back to the DOM, which is in turn passed back to jQuery (assuming you’ve hooked an event).

It should be simple enough to convert the function to work with Prototype or YUI or the library (or not) of your choice.

Wrap up.

I would only recommend using this technique when you absolutely must, because by adding the onclick attribute, you’re mixing behaviour with presentation. There are articles explaining why this is a best practise but I believe, in the right situation, it can benefit the user.

to hex

d.toString(16)

Beautifully simple way to get a hex value from a number. Note that d is a number. If you want a string as a hex XML valid code, use:

'&#x' + parseInt(number).toString(16).toUpperCase() + ';'

ps ax | grep lookupd | grep -v grep | perl -ne 'split; print $_[0]' | xargs sudo kill -HUP

I’m often connecting to different networks depending on what job I’m doing, and sometimes I’ll need to tweak my /etc/hosts file. Since my system will cache DNS lookups, I’ll need to restart lookupd, and this command does it in one hit.

Cameron Moll gave a presentation at dConstruct 2007.

At one point during the presentation, he demonstrated how he checked that the typography still held the weight on the National Gazette front page redesign (pg. 42).

Since they’re fun nuggets of code, I’ve written a simple bookmarklet that strips colour, images and background decoration from the page, leaving you just the content and typography.

Plainify

Drag and drop the ‘plainify’ link to your bookmark bar to install.