[IMP] utils: add loadJS function

Very useful to lazy load libraries in owl applications
This commit is contained in:
Géry Debongnie
2019-04-26 12:47:25 +02:00
parent c405dadc1b
commit 78108e8d2c
+24 -1
View File
@@ -164,4 +164,27 @@ export async function loadTemplates(url: string): Promise<string> {
let templates = await result.text();
templates = templates.replace(/<!--[\s\S]*?-->/g, "");
return templates;
}
}
const loadedScripts: { [key: string]: Promise<void> } = {};
export function loadJS(url: string): Promise<void> {
if (url in loadedScripts) {
return loadedScripts[url];
}
const promise: Promise<void> = new Promise(function(resolve, reject) {
const script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
script.onload = function() {
resolve();
};
script.onerror = function() {
reject(`Error loading file '${url}'`);
};
const head = document.head || document.getElementsByTagName("head")[0];
head.appendChild(script);
});
loadedScripts[url] = promise;
return promise;
}