Javascript 延迟脚本加载,直到承诺完成
有没有办法延迟脚本标记的onload事件,直到脚本中的某个承诺完成 一点背景:我加载了一个带有以下函数的脚本。在脚本中调用了一些异步函数,该函数返回一个值Javascript 延迟脚本加载,直到承诺完成,javascript,asynchronous,Javascript,Asynchronous,有没有办法延迟脚本标记的onload事件,直到脚本中的某个承诺完成 一点背景:我加载了一个带有以下函数的脚本。在脚本中调用了一些异步函数,该函数返回一个值 const loadScript=(src,resolveWithGlobal)=> 新承诺((决议)=>{ 常量脚本=window.document.createElement(“脚本”); script.src=src; script.async=true; script.onload=()=>{ 解析(窗口[resolveWithGlo
const loadScript=(src,resolveWithGlobal)=>
新承诺((决议)=>{
常量脚本=window.document.createElement(“脚本”);
script.src=src;
script.async=true;
script.onload=()=>{
解析(窗口[resolveWithGlobal]);
};
window.document.body.appendChild(脚本);
});
const lib=await loadScript(“path/to/library1.js”、“library2”);
加载的脚本与此脚本类似(其行为类似于加载其他脚本/库的代理)
//library1.js
(异步()=>{
等待加载脚本(“path/to/library2.js”、“library2”);
})();
目前我只返回WARE以查找并在同一个文件中执行两个loadScript
调用,如果我以后要删除间接寻址,这有点难看
const lib1 = loadScript("lib1.js", "lib1");
const lib = loadScript(lib.path, "lib2");
对于一般情况,您可以将解析器函数放在窗口上,使用一些不会与其他名称冲突的名称-可能会将随机字符串放在脚本标记的数据集中。然后让脚本在运行时检查其脚本标记的唯一名称,并在异步操作完成时调用解析器
const loadScript = (src, resolveWithGlobal) =>
new Promise((resolve) => {
const script = window.document.createElement("script");
script.src = src;
script.async = true;
const uniqueId = Math.random().toString(36).substring(7);
script.dataset.uniqueId = uniqueId;
window[uniqueId] = () => {
delete window[uniqueId]
return () => {
resolve(window[resolveWithGlobal]);
};
};
script.onload = () => {
// If resolver hasn't been retrieved by the library, do it now:
window[uniqueId]?.()();
};
window.document.body.appendChild(script);
});
如果脚本不执行任何异步操作,则不需要对窗口上的解析器执行任何特殊操作-loadScript
将在脚本加载时调用它
const lib1 = loadScript("lib1.js", "lib1");
// lib1.js
const resolve = window[document.currentScript.uniqueid]();
loadScript("path/to/library2.js", "library2")
.then(resolve);