我正在构建一个解决方案,其中多个 Javascript 库根据用户的交互在不同的时间点动态加载。库加载后,执行库中的脚本。
例如:
let script1 = '<script class="'+script_class+'" id="' + script_id + '" type="text/javascript" src="' + some_script_url +'"></script>';
$("head").append(script1);
let script2 = '<script class="'+script_class+'" id="' + script_id + '" type="text/javascript" src="' + some_script_url +'"></script>';
$("head").append(script2);
let script3 = '<script class="'+script_class+'" id="' + script_id + '" type="text/javascript" src="' + some_script_url +'"></script>';
$("head").append(script3);
然后函数将执行脚本内的函数:
function doSomething() {
scriptFunction();
}
doSomething();
问题是有时在函数尝试执行之前脚本不会被加载。这会导致错误,例如“找不到 scriptFunction”。在执行脚本之前如何等待每个库加载?这可以用承诺来完成吗?
这是一个返回承诺的函数,该承诺在脚本加载时解析:
function loadScript(src) {
return new Promise(resolve => {
const script = document.createElement("script");
script.setAttribute("async", "");
script.onload = resolve;
script.setAttribute("src", src);
document.head.appendChild(script);
});
}
const urls = [
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js"
];
Promise.all(urls.map(loadScript)).then(ready);
function ready() {
console.log("all loaded");
console.log($.fn.jquery);
console.log(luxon.DateTime.now().toString());
}