-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloadJSON.js
38 lines (35 loc) · 1.15 KB
/
loadJSON.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
(() => {
const jsons = document.querySelectorAll('script[json]');
window.awaitJSON = window.awaitJSON || {};
window.getLoadedJSON = (objectName) => {
if (objectName in window.awaitJSON)
return window.awaitJSON[objectName];
return Promise.resolve(window[objectName])
};
for (const i in jsons) {
if (!jsons[i] || !jsons[i].getAttribute) continue;
const j = jsons[i];
const jsonPath = j.getAttribute('json');
const objName = j.getAttribute('jsonObject');
const callbackName = j.getAttribute('jsonCallback');
const callback = window[callbackName] || null;
if (!objName && !callbackName)
continue;
const fetchPromise = fetch(jsonPath)
.then(response => response.json())
.then(json => {
deleteAwaiter()
if (typeof callback === 'function')
callback(json);
if (objName)
window[objName] = json;
return json;
})
// eslint-disable-next-line no-console
.catch(console.error);
window.awaitJSON[objName || callbackName] = fetchPromise
const deleteAwaiter = () => {
delete window.awaitJSON[objName || callbackName]
}
}
})()