JSON(P) Stacking

December 6, 2009

JSONP was proposed as grabbing data from external domains avoiding the cross script scripting limitations (see this Ajaxian article for more information). It requires a call to an external API where you specificy the a callback function, you do this through the use of script tag. For example:

<script type="text/javascript" src="http://yourdomain.com/api?callback=myfunction"></script>

When the script tag has been loaded your function would be called with the JSON data, like so.

myfunction('some JSON data');

However you become reliant on that external service to always be available, if for any reason that service goes down you wouldn’t get any data and your page would be likely to hang.

Therefore I propose a system of JSONP stacking, quite simply you stack up your JSON requests if you don’t receive a response in a set time it will stop the request.

This can be easily achieved by having the following function:

// callback function
var _c = false;
// success flag
var _s = false;

function JSONPStacking(url, callback) {
	// create the element
	var script = document.createElement('script');
	// set the source
	script.src = url + '&amp;callback=callback';
	// render the element
	document.appendChild(script);
	// start the counter, this one last for 5 seconds
	setTimeout(function() {
		if (!_s) {
			// remove the element
			document.body.removeChild(script);
		}
	}, 5000);
}

function callback(data) {
	// say the data has been received
	_s = true;
	// call the callback with the data
	_c(data);
}

Basically what we are doing here is to create a normal JSONP request by creating a script tag and loading it into the body. However we are overriding the standard callback function with our own one, callback. When the request succeeds this will call that function with the data and in turn we call our success function. If 5 seconds have past the timeout will trigger, see if the success flag has been set if not it will remove the element from the DOM thereby stopping the request.

That's it, it is a really simple principle but will hopefully stop your site from hanging on long request, such as for the Twitter widget. It will also make your widgets that you build a lot more stable and won't overload your site.

Comments

comments powered by Disqus