Skip to content

Instantly share code, notes, and snippets.

@Anmo
Forked from JosePedroDias/jsonp.js
Last active August 29, 2015 14:07
Show Gist options
  • Save Anmo/fc8af5d1e944296dc5b2 to your computer and use it in GitHub Desktop.
Save Anmo/fc8af5d1e944296dc5b2 to your computer and use it in GitHub Desktop.
window.jsonpCbs = { };
var jsonp = function( o ) {
var key = 'cb' + Math.floor( Math.random( ) * 100000 );
var sep = o.uri.indexOf( '?' ) < 0 ? '?' : '&';
var scriptEl = document.createElement( 'script' );
scriptEl.setAttribute( 'type' , 'text/javascript' );
scriptEl.setAttribute( 'src' , [ o.uri , sep , o.jsonp || 'jsonp' , '=jsonpCbs.' , key ].join( '' ) );
var sto;
var clear = function( ) {
delete window.jsonpCbs[key];
scriptEl.parentNode.removeChild( scriptEl );//Seppuku
clearTimeout( sto );
};
var errorCb = function( err ) {
return function( ) {
o.cb.call( null , err );
clear( );
}
};
var sto = setTimeout( errorCb({
error : 'Request Timeout' ,
code : 408
}) , o.timeout || 4000 );
scriptEl.onerror = errorCb({
error : 'Bad Request' ,
code : 400
});
window.jsonpCbs[ key ] = function( ) {
o.cb.apply( null , arguments );
clear( );
};
document.head.appendChild( scriptEl );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment