const ModulePromiseCache = {};
async function loadESModule(url, moduleFromGlobalScope) {
    if (ModulePromiseCache[url] !== undefined) {
        return ModulePromiseCache[url];
    }
    ModulePromiseCache[url] = loadESModuleFromNetwork(url, moduleFromGlobalScope);
    return ModulePromiseCache[url];
}
function loadESModuleFromNetwork(url, moduleFromGlobalScope) {
    return new Promise((resolve, reject)=>{
        const maybeScript = findScript(url);
        if (maybeScript && maybeScript.dataset.loaded === 'true') {
            try {
                resolve(moduleFromGlobalScope());
            } catch (err) {
                return reject(new Error(`${url} already loaded, but module was not found in global scope: ${err}`));
            }
        }
        const script = createScript(url);
        script.addEventListener('load', ()=>{
            script.dataset.loaded = 'true';
            try {
                resolve(moduleFromGlobalScope());
            } catch (err) {
                reject(new Error(`${url} was loaded, but module was not found in global scope: ${err}`));
            }
        });
        script.addEventListener('error', (err)=>{
            reject(new Error(`${url} could not be loaded: ${err}`));
        });
    });
}
const findScriptsInDom = (url)=>document.querySelectorAll(`script[src="${url}"]`);
function findScript(url) {
    const scripts = findScriptsInDom(url);
    if (scripts[0]) {
        return scripts[0];
    }
}
function createScript(url) {
    const script = document.createElement('script');
    script.setAttribute('src', url);
    script.setAttribute('async', 'true');
    script.setAttribute('defer', 'true');
    document.head.appendChild(script);
    return script;
}

export { loadESModule };
//# sourceMappingURL=loadESModule.mjs.map
