-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsonp.js
52 lines (46 loc) · 1.41 KB
/
jsonp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* @author Max L Dolgov <[email protected]>
* @license MIT
*
* JSONP simple utility
* @param options
* - **`url`** - `{string}` - request's URL
* - **`success`** - `{function(<object>)}` - callback for response handling
* - **`cbParamName:`** - '{string}' - will be passed to server as callback='jsonp' URL-param
* - **`cbName:`** - '{string}' - will be used as a prefix for callbacks naming in global scope
*
*/
function JSONP (options) {
var cbName = options && options.cbName || 'smjcb',
callbackParamName = options.cbParamName || 'callback';
if (!(cbName in JSONP)) {
JSONP[cbName] = 0;
}
var script = document.createElement('script'),
callback = '' + cbName + JSONP[cbName]++;
function cleanup() {
if (script && script.parentNode) { script.parentNode.removeChild(script); }
if (callback in window) {
try {
delete window[callback];
} catch (e) {
window[callback] = undefined; // IE8 support
}
}
}
window[callback] = function() {
cleanup();
if (options.success) {
return options.success.apply(null, arguments);
}
};
var appender = options.url.indexOf('?') == -1 ? '?' : '&';
script.src = options.url + appender + callbackParamName + '=' + callback;
script.async = true;
script.onerror = function() {
cleanup();
if (options.error) { options.error.apply(null, arguments); }
};
(document.head || document.body).appendChild(script);
}
module.exports = JSONP;