Last active
August 29, 2015 13:56
-
-
Save adriengibrat/8913989 to your computer and use it in GitHub Desktop.
Lightweight standalone jsonP utility (jQuery like)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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