* JSONP handler * * Options: * - param {String} qs parameter (`callback`) * - prefix {String} qs parameter (`__jp`) * - name {String} qs parameter (`prefix` + incr) * - timeout {Number} how long after a timeout error is emitted (`60000`) * * @param {String} url * @param {Object|Function
(url, opts, fn)
| 37 | */ |
| 38 | |
| 39 | function jsonp(url, opts, fn){ |
| 40 | if ('function' == typeof opts) { |
| 41 | fn = opts; |
| 42 | opts = {}; |
| 43 | } |
| 44 | if (!opts) opts = {}; |
| 45 | |
| 46 | var prefix = opts.prefix || '__jp'; |
| 47 | |
| 48 | // use the callback name that was passed if one was provided. |
| 49 | // otherwise generate a unique name by incrementing our counter. |
| 50 | var id = opts.name || (prefix + (count++)); |
| 51 | |
| 52 | var param = opts.param || 'callback'; |
| 53 | var timeout = null != opts.timeout ? opts.timeout : 60000; |
| 54 | var enc = encodeURIComponent; |
| 55 | var target = document.getElementsByTagName('script')[0] || document.head; |
| 56 | var script; |
| 57 | var timer; |
| 58 | |
| 59 | |
| 60 | if (timeout) { |
| 61 | timer = setTimeout(function(){ |
| 62 | cleanup(); |
| 63 | if (fn) fn(new Error('Timeout')); |
| 64 | }, timeout); |
| 65 | } |
| 66 | |
| 67 | function cleanup(){ |
| 68 | if (script.parentNode) script.parentNode.removeChild(script); |
| 69 | window[id] = noop; |
| 70 | if (timer) clearTimeout(timer); |
| 71 | } |
| 72 | |
| 73 | function cancel(){ |
| 74 | if (window[id]) { |
| 75 | cleanup(); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | window[id] = function(data){ |
| 80 | debug('jsonp got', data); |
| 81 | cleanup(); |
| 82 | if (fn) fn(null, data); |
| 83 | }; |
| 84 | |
| 85 | // add qs component |
| 86 | url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id); |
| 87 | url = url.replace('?&', '?'); |
| 88 | |
| 89 | debug('jsonp req "%s"', url); |
| 90 | |
| 91 | // create script |
| 92 | script = document.createElement('script'); |
| 93 | script.src = url; |
| 94 | target.parentNode.insertBefore(script, target); |
| 95 | |
| 96 | return cancel; |