-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch-inject.js
40 lines (39 loc) · 1.36 KB
/
fetch-inject.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
/*! Fetch Inject | Copyright (C) VHS <vhsdev@tutanota.com> | @license Zlib */
const injector=function(i,n,j,e,c,t,s){t=n.createElement(j);j==="template"?(t.innerHTML=e.text,n.head.appendChild(t.content.cloneNode(!0)),c(e)):(s=n.getElementsByTagName(j)[0],t.appendChild(n.createTextNode(e.text)),t.onload=c(e),s?s.parentNode.insertBefore(t,s):n.head.appendChild(t))}; // prettier-ignore
export default async (inputs, promise, { fetch } = globalThis) => {
const resources = [];
const deferreds = promise ? [].concat(promise) : [];
const thenables = [];
inputs.forEach((input) =>
deferreds.push(
fetch(input)
.then((res) => Promise.all([res.clone().text(), res.blob()]))
.then(async ([text, blob]) => {
resources.push({ text, blob });
})
)
);
await Promise.all(deferreds);
resources.forEach((resource) =>
thenables.push({
then: (resolve) => {
let type = 'script';
const mimeToElementType = new Map([
['text/html', 'template'],
['text/css', 'style'],
['application/javascript', 'script']
]);
for (const [mime, elementType] of mimeToElementType) {
if (resource.blob.type.startsWith(mime)) {
type = elementType;
break;
}
}
typeof document !== 'undefined'
? injector(globalThis, document, type, resource, resolve)
: resolve(resource);
}
})
);
return await Promise.all(thenables);
};