-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJSONLoader.ts
More file actions
36 lines (31 loc) · 994 Bytes
/
JSONLoader.ts
File metadata and controls
36 lines (31 loc) · 994 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
31
32
33
34
35
36
interface XHR extends XMLHttpRequest {
readyState: number;
status: number;
responseText: string;
}
interface WindowWithActiveX extends Window {
ActiveXObject: new (type: string) => XHR;
}
type Callback = (error: Error | null, data: any) => void;
export function load(location: string, callback: Callback): void {
const xhr = getXHR();
xhr.open('GET', location, true);
xhr.onreadystatechange = createStateChangeListener(xhr, callback);
xhr.send();
}
function createStateChangeListener(xhr: XHR, callback: Callback): () => void {
return function() {
if (xhr.readyState === 4 && xhr.status === 200) {
try {
callback(null, JSON.parse(xhr.responseText));
} catch (err) {
callback(err instanceof Error ? err : new Error(String(err)), null);
}
}
};
}
function getXHR(): XHR {
return window.XMLHttpRequest
? new window.XMLHttpRequest()
: new ((window as unknown) as WindowWithActiveX).ActiveXObject('Microsoft.XMLHTTP');
}