This repository has been archived by the owner on Apr 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjsonp.js
103 lines (69 loc) · 1.84 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
100
101
102
103
/**
* Darrell Huffman, 2017-04-02
**/
export default function ( url ) {
/**
* Create a script element
*
* Params:
*
* url (string)
* callback (string)
**/
this.createScript = ( url, callback ) => {
const script = document.createElement('script');
script.src = url + callback;
return script;
};
/**
* Remove a script element from the DOM
*
* Params:
*
* script (DOM node)
**/
this.removeScript = ( script ) => {
script.parentNode.removeChild( script );
};
/**
* Error message that is passed if the promise is rejected
**/
this.error = new Error( 'The requested script failed to load.' );
return new Promise( ( resolve, reject ) => {
/**
* Create a name for the JSONP callback function
**/
const callback = 'fn' + Date.now();
/**
* Bolt the callback to the window object
**/
window[ callback ] = ( JSON ) => {
/**
* Pass the JSON data if the promise was resolved
**/
resolve( JSON );
/**
* Tidy up by deleting the callback from the window object
**/
delete window[ callback ];
};
/**
* Create the script
*
* If the script fails to load, the promise is rejected and the error is passed
*
* If the script loads successfully, it is removed thereafter so as to keep the DOM tidy
**/
const script = this.createScript( url, callback );
script.addEventListener( 'error', () => {
reject( this.error );
}, false );
script.addEventListener( 'load', () => {
this.removeScript( script );
}, false );
/**
* Append the script to the document.head
**/
document.head.appendChild( script );
} );
};