This script dynamically generates and deletes script tags, along with the global variable it needs, once a specific call is completed.
An alternative option could be utilizing CORS to permit requests other than just GET requests; however, this feature isn't compatible with older browsers.
To prevent race conditions or performance issues over a slow network, you could allow the JSONP callback to recursively invoke the function, triggering a new call only if the callback is returned. You may also consider incorporating an optional setTimeout
function to ensure there's a minimum delay.
The code snippet below demonstrates retrieving a specific page revision and its user using Wikipedia's API.
<script>
var JSONP = function(global){
// (C) WebReflection Essential - Mit Style ( http://webreflection.blogspot.com/2011/02/all-you-need-for-jsonp.html )
// 202 bytes minified + gzipped via Google Closure Compiler
function JSONP(uri, callback) {
function JSONPResponse() {
try { delete global[src] } catch(e) { global[src] = null }
documentElement.removeChild(script);
callback.apply(this, arguments);
}
var
src = prefix + id++,
script = document.createElement("script")
;
global[src] = JSONPResponse;
documentElement.insertBefore(
script,
documentElement.lastChild
).src = uri + "=" + src;
}
var
id = 0,
prefix = "__JSONP__",
document = global.document,
documentElement = document.documentElement
;
return JSONP;
}(this);
// Ensure to add the callback parameter at the end
function startAPI (start) {
start = start || new Date();
var url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Main%20Page&rvprop=timestamp|user|comment|content&format=json&callback';
var minimum = 10000;
function execute (str) {
alert(str);
}
JSONP(url, function (obj) {
for (var pageNo in obj.query.pages) {
var page = obj.query.pages[pageNo];
var str = 'The user ' + page.revisions[0]['user'] + ' left the page with this code ' + page.revisions[0]['*'];
execute(str);
var elapsed = (new Date().getTime()) - start;
setTimeout(startAPI, (elapsed < minimum) ? (minimum - elapsed) : 0);
break;
}
});
}
startAPI();
</script>