Skip to content

Instantly share code, notes, and snippets.

@adriengibrat
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adriengibrat/8913989 to your computer and use it in GitHub Desktop.
Save adriengibrat/8913989 to your computer and use it in GitHub Desktop.
Lightweight standalone jsonP utility (jQuery like)
window.jsonP = function ( url, callback, paramName ) {
var self = arguments.callee // this function
, queue = self.queue || ( self.queue = {} ) // callback queue
, name = 'jsonP' + Object.keys( queue ).length + '_' + Date.now() // unique callback name
, global = 'jsonP.queue.' + name // global callback name
, placeholder = /(=)\?(?=&|$)/ // placeholder pattern
, script = document.createElement( 'script' ) // script dom node
;
script.type = 'text/javascript';
script.src = placeholder.test( url ) ?
url.replace( placeholder, '$1' + global ) :
url + ( /\?/.test(url) ? '&' : '?' ) + ( paramName || 'callback' ) + '=' + global
;
script.onload = function () {
delete queue[name];
};
script.onreadystatechange = function() { // IE sucks
this.readyState == 'complete' && this.onload();
};
queue[name] = callback;
( document.getElementsByTagName('head')[0] || document.documentElement ).appendChild( script );
};
window.jsonP=function(a,b,c){var d=arguments.callee,e=d.queue||(d.queue={}),f="jsonP"+Object.keys(e).length+"_"+Date.now(),g="jsonP.queue."+f,h=/(=)\?(?=&|$)/,i=document.createElement("script");i.type="text/javascript",i.src=h.test(a)?a.replace(h,"$1"+g):a+(/\?/.test(a)?"&":"?")+(c||"callback")+"="+g,i.onload=function(){delete e[f]},i.onreadystatechange=function(){"complete"==this.readyState&&this.onload()},e[f]=b,(document.getElementsByTagName("head")[0]||document.documentElement).appendChild(i)};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment