I've used this function in the past:
const loadScriptAsync = (() => {
"use strict";
const loadedScripts = {};
const loadScriptCore = (src) => {
const script = document.createElement("script");
return new Promise((resolve, reject) => {
script.onload = () => resolve(true);
script.onerror = (e) => reject(e);
script.src = src;
document.body.appendChild(script);
});
};
return (src) => {
if (loadedScripts.hasOwnProperty(src)) {
return loadedScripts[src];
}
const result = loadScriptCore(src);
loadedScripts[src] = result;
return result;
};
})();
You can either chain the additional code in the
.then
callback to
the Promise[
^]:
loadScriptAsync(src).then(() => { ... });
or
use async
/ await
[
^]:
(async () => {
await loadScriptAsync(src);
...
})();