forked from unbug/codelf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONP.js
More file actions
30 lines (30 loc) · 982 Bytes
/
JSONP.js
File metadata and controls
30 lines (30 loc) · 982 Bytes
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
const JSONP = (url, options) => {
options = options || {};
url = options.url || url;
return new Promise((resolve, reject) => {
let timer = 0;
let script = document.createElement('script');
const callbackName = options.callbackName || `__jsonp_${Date.now()}_callback`;
url = url.replace('=?', `=${callbackName}${options.nocache ? ('&_=' + Date.now()) : ''}`);
const done = () => {
window.clearTimeout(timer);
try {document.head.removeChild(script);} catch (e) {}
window[callbackName] = null;
};
const onerror = () => {
window.removeEventListener('error', onerror);
done();
reject();
};
window[callbackName] = (...args) => {
done();
resolve(...args);
};
timer = setTimeout(onerror, 5 * 60 * 1000); // timeout in 5 min
window.addEventListener('error', onerror);
script.onerror = onerror;
script.src = url;
document.head.appendChild(script);
});
}
export default JSONP;