Posts Tagged ‘json webservices’

SleepyCod
by SleepyCod

Dazzling performance with JSONP and Swell

Posted in Javascript, Swell

For an upcoming work we figured it would be useful to add JSONP support in our Asset component in order to load the given URL and once loaded, passback the JSON to a handler with the content.

What’s interesting with this approach is that we don’t rely on any hack to get the response such as evaluating all the script files in head or loading the content asynchronously then appending it.

There are numerous advantages using our solution :

  • You can load the JSON from multiple sources but keep a single handler, each JSONP file processed will be passed back as an argument
  • You can have a single handler for the whole sequence or listen events of each JSONP file being loaded with CustomEvents
  • The tags are removed from the DOM once loaded, this avoid memleaks or JSONP collision
  • This approach is robust and works equally between browsers even on old ones like MSIE 5.5

here’s a little example of what can be done:

Swell.Core.Asset.load('jsonp', [
    'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=rideback&output=json&callback=',
    'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=saintseiya&output=json&callback='
], function() {
    for(var _n = 0; _n < arguments.length; _n++) {
        var yim = arguments[_n];
        for(var _i = 0, _im; _im = yim.ResultSet.Result[_i++];) {
            html.img({
                'src'   : _im.Thumbnail.Url,
                'alt'   : _im.Title,
                'title' : _im.Title,
                'width' : _im.Thumbnail.Width,
                'height': _im.Thumbnail.Height
            }).appendTo('receiver');
        }
    }
});