-
Notifications
You must be signed in to change notification settings - Fork 17
/
jsonp.js
executable file
·99 lines (88 loc) · 2.42 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict'
/*!
* Lightweight JSONP fetcher
* Copyright 2010-2019 Erik Arenhill. All rights reserved.
* BSD Zero Clause License
*/
var JSONP = (function(window){
var counter = 0, head, config = {};
function load(url, onTimeout) {
var script = document.createElement('script'),
done = false,
timeoutTimer = null;
script.src = url;
script.async = true;
var errorHandler = config.error;
if ( typeof errorHandler === 'function' ) {
script.onerror = function(ex){
_clearTimeout();
errorHandler({url: url, event: ex});
};
}
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) {
done = true;
_clearTimeout();
script.onload = script.onreadystatechange = null;
if ( script && script.parentNode ) {
script.parentNode.removeChild( script );
}
}
};
function _clearTimeout(){
clearTimeout(timeoutTimer);
timeoutTimer = null;
}
function triggerTimeout() {
if ( typeof errorHandler === 'function' ) {
errorHandler({url: url, event: new Error('Timeout')})
onTimeout();
}
}
if ( config.timeout ) {
timeoutTimer = setTimeout(triggerTimeout, config.timeout)
}
if ( !head ) {
head = document.getElementsByTagName('head')[0];
}
head.appendChild( script );
}
function encode(str) {
return encodeURIComponent(str);
}
function jsonp(url, params, callback, callbackName) {
var query = (url||'').indexOf('?') === -1 ? '?' : '&', key;
callbackName = (callbackName||config['callbackName']||'callback');
if ( !config['callbackName'] ) {
callbackName = callbackName + '_jsonp_' + (++counter);
}
params = params || {};
for ( key in params ) {
if ( params.hasOwnProperty(key) ) {
query += encode(key) + '=' + encode(params[key]) + '&';
}
}
var didTimeout = false;
window[ callbackName ] = function(data){
if ( !didTimeout ) {
callback(data);
}
try {
delete window[ callbackName ];
} catch (e) {}
window[ callbackName ] = null;
};
load(url + query + 'callback=' + callbackName, function(){didTimeout = true;});
return callbackName;
}
function setDefaults(obj){
config = obj;
}
return {
get:jsonp,
init:setDefaults
}
}(window))
if ( typeof module !== 'undefined' ) {
module.exports = JSONP
}