第一次使用pica()
时,它将加载外部库。但是,如果在完成加载外部JS之前第二次使用pica()
,则不应再次加载库,以便alert()
运行。
let picaStatus = 0;
function pica(...args) {
if (picaStatus == 1) { // library previously loaded
pica.resizeCanvas(...args);
} else if (picaStatus == 0) { // library hasn't been loaded
picaStatus = -1;
$.getScript("//cdnjs.cloudflare.com/ajax/libs/pica/2.0.4/pica.min.js", () => {
picaStatus = 1;
pica.resizeCanvas(...args);
});
} else if (picaStatus == -1) { // library is currently being loaded by another call
alert('loading collision');
}
}
除了抛出alert()
并删除函数调用之外,如何让第二个函数调用等到库加载完毕?
答案 0 :(得分:1)
使状态成为已加载脚本的承诺:
let picaStatus = null;
function pica(...args) {
if (!picaStatus) { // library hasn't been loaded
picaStatus = $.getScript("//cdnjs.cloudflare.com/ajax/libs/pica/2.0.4/pica.min.js");
}
picaStatus.then(() => {
pica.resizeCanvas(...args);
});
}
答案 1 :(得分:1)
通常不建议使用阻塞函数调用来加载资源。相反,您应该通过使用回调或承诺来利用JavaScript的异步特性。您可能也不想将函数的状态存储在某种全局变量中,因此您应该使用IIFE来包装该状态。
const pica = (function() {
let picaScript;
return function(...args) {
picaScript = picaScript ||
$.getScript("//cdnjs.cloudflare.com/ajax/libs/pica/2.0.4/pica.min.js");
picaScript.then(() => pica.resizeCanvas(...args));
};
})();