Skip to content

Instantly share code, notes, and snippets.

@DC3
Last active August 29, 2015 14:23
Show Gist options
  • Save DC3/bd8e17273ad6b2770d6c to your computer and use it in GitHub Desktop.
Save DC3/bd8e17273ad6b2770d6c to your computer and use it in GitHub Desktop.
JSONP = do (win = window, doc = document) ->
head = doc.getElementsByTagName('head')[0]
createScript = (url) ->
node = doc.createElement('script')
node.onload = -> head.removeChild node
node.onerror = ->
head.removeChild node
throw new Error 'JSONP load script error'
node.src = url
head.appendChild node
genCallbackName = do ->
expando = 'CB'+(''+Math.random()).replace( /\D/g, "")
callbackId = 0
-> [expando, callbackId++].join('_')
genGlobalCallback = (callbackName, fn) ->
win[callbackName] = ->
try
fn arguments...
catch error
throw new Error 'JSONP genGlobalCallback can not apply function'
delete win[callbackName]
(url, fn, paramName = 'callback') ->
cbName = genCallbackName()
symbol = if /\?/.test(url) then '&' else '?'
cbUrl = [url, symbol, paramName, '=', cbName].join('')
cb = genGlobalCallback cbName, fn
createScript(cbUrl, cb)
#log = console.log.bind('JSONP: ') # can not apply bind function
log = ->
console.count 'done'
console.log 'done', arguments...
# TestCase
JSONP('http://ip.jsontest.com/', log)
JSONP('http://ip.jsontest.com/?mime=5', log)
// Generated by CoffeeScript 1.9.3
(function() {
var JSONP, log;
var slice = [].slice;
JSONP = (function(win, doc) {
var createScript, genCallbackName, genGlobalCallback, head;
head = doc.getElementsByTagName('head')[0];
createScript = function(url) {
var node;
node = doc.createElement('script');
node.onload = function() {
return head.removeChild(node);
};
node.onerror = function() {
head.removeChild(node);
throw new Error('JSONP load script error');
};
node.src = url;
return head.appendChild(node);
};
genCallbackName = (function() {
var callbackId, expando;
expando = 'CB' + ('' + Math.random()).replace(/\D/g, "");
callbackId = 0;
return function() {
return [expando, callbackId++].join('_');
};
})();
genGlobalCallback = function(callbackName, fn) {
return win[callbackName] = function() {
var error;
try {
fn.apply(null, arguments);
} catch (_error) {
error = _error;
throw new Error('JSONP genGlobalCallback can not apply function');
}
return delete win[callbackName];
};
};
return function(url, fn, paramName) {
var cb, cbName, cbUrl, symbol;
if (paramName == null) {
paramName = 'callback';
}
cbName = genCallbackName();
symbol = /\?/.test(url) ? '&' : '?';
cbUrl = [url, symbol, paramName, '=', cbName].join('');
cb = genGlobalCallback(cbName, fn);
return createScript(cbUrl, cb);
};
})(window, document);
log = function() {
console.count('done');
return console.log.apply(console, ['done'].concat(slice.call(arguments)));
};
JSONP('http://ip.jsontest.com/', log);
return JSONP('http://ip.jsontest.com/?mime=5', log);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment