UNPKG

1.78 kBJavaScriptView Raw
1/**
2 * Callback index.
3 */
4
5var count = 0;
6
7/**
8 * Noop function.
9 */
10
11function noop() {}
12
13/**
14 * JSONP handler
15 *
16 * Options:
17 * - param {String} qs parameter (`callback`)
18 * - prefix {String} qs parameter (`__jp`)
19 * - name {String} qs parameter (`prefix` + incr)
20 * - timeout {Number} how long after a timeout error is emitted (`60000`)
21 *
22 * @param {String} url
23 * @param {Object|Function} optional options / callback
24 * @param {Function} optional callback
25 */
26
27function jsonp(url, opts, fn) {
28 if ('function' === typeof opts) {
29 fn = opts;
30 opts = {};
31 }
32 if (!opts) opts = {};
33
34 var prefix = opts.prefix || '__jp';
35
36 // use the callback name that was passed if one was provided.
37 // otherwise generate a unique name by incrementing our counter.
38 var id = opts.name || prefix + count++;
39
40 var param = opts.param || 'callback';
41 var timeout = null != opts.timeout ? opts.timeout : 60000;
42 var enc = encodeURIComponent;
43 var target = document.getElementsByTagName('script')[0] || document.head;
44 var script;
45 var timer;
46
47 if (timeout) {
48 timer = setTimeout(function () {
49 cleanup();
50 if (fn) fn(new Error('Timeout'));
51 }, timeout);
52 }
53
54 function cleanup() {
55 if (script.parentNode) script.parentNode.removeChild(script);
56 window[id] = noop;
57 if (timer) clearTimeout(timer);
58 }
59
60 function cancel() {
61 if (window[id]) {
62 cleanup();
63 }
64 }
65
66 window[id] = function (data) {
67 cleanup();
68 if (fn) fn(null, data);
69 };
70
71 // add qs component
72 url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id);
73 url = url.replace('?&', '?');
74
75 // create script
76 script = document.createElement('script');
77 script.src = url;
78 target.parentNode.insertBefore(script, target);
79
80 return cancel;
81}
82
83export default jsonp;
\No newline at end of file