我正在构建一个解决方案,其中多个 Javascript 库根据用户的交互在不同的时间点动态加载。库加载后,执行库中的脚本。
例如:
let script1 = '<script src="' + some_script_url_1 +'"></script>';
$("head").append(script1);
let script2 = '<script src="' + some_script_url_2 +'"></script>';
$("head").append(script2);
let script3 = '<script src="' + some_script_url_3 +'"></script>';
$("head").append(script3);
然后一些代码将执行在加载的脚本中定义的函数:
scriptFunction(); // This function is defined in the dynamically loaded library
问题是有时在函数尝试执行之前脚本不会被加载。这会导致诸如“
scriptFunction
未找到”之类的错误。在执行脚本之前如何等待每个库加载?这可以用承诺来完成吗?
这是一个返回承诺的函数,该承诺在脚本加载时解析:
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.onload = resolve;
script.onerror = reject;
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,
err => console.log("Error loading", err.target.src));
function ready() {
console.log("all loaded");
console.log($.fn.jquery);
console.log(luxon.DateTime.now().toString());
}