1 |
|
2 |
|
3 |
|
4 |
|
5 | var count = 0;
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | function noop() {}
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | function 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 |
|
37 |
|
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 |
|
72 | url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id);
|
73 | url = url.replace('?&', '?');
|
74 |
|
75 |
|
76 | script = document.createElement('script');
|
77 | script.src = url;
|
78 | target.parentNode.insertBefore(script, target);
|
79 |
|
80 | return cancel;
|
81 | }
|
82 |
|
83 | export default jsonp; |
\ | No newline at end of file |