首先,我要指出,这需要使用纯净的原始Javascript来完成,而没有第三方库或框架(很可能不是JQuery)。假设我有一个名为included_script.js的JS文件,其内容如下:function sayIt() { alert("Hello!");}现在说我有以下简化的JS函数,该函数加载外部JS文件并尝试执行其中定义的sayIt函数:function loadIt() { var externalScript = document.createElement("script"); externalScript.type = "text/javascript"; externalScript.src = "js/included_script.js"; document.getElementsByTagName("head")[0].appendChild(externalScript); /* BLOCK HERE, and do not continue until externalScript (included_script.js) has been completely loaded from the server and included into the document, so that the following execution of 'sayIt' actually works as expected. */ sayIt(); /*I expect the "Hello!" alert here, but 'sayIt' is undefined (which I think - but am not 100% sure - is because this line is reached before externalScript (included_script.js) is fully downloaded from the server). */}请注意,在将externalScript附加到头部之前,我已经尝试过诸如externalScript.setAttribute("defer", "defer"),externalScript.setAttribute("async", "async")(即使我知道这是多余的)之类的东西。还要注意,回调不适合使用。如何在上面显示的“此处阻止”部分中使功能loadIt阻塞,直到externalScript (included_script.js)完全下载到客户端,以便在sayIt externalScript中定义的(included_script.js)函数在以下情况下真正起作用从功能loadIt调用?基于BOBRODES的BRILLIANT,简单答案的更新:included_script.js仍然具有以下内容:function sayIt() { alert("Hello!");}现在将loadIt变成一类(比这复杂得多,但这显示了其工作所需的准系统机制):function loadIt() { this.loadExternal = async function() { return new Promise( function(resolve, reject) { try { var externalScript = document.createElement("script"); externalScript.type = "text/javascript"; externalScript.src = "js/included_script.js"; if (externalScript.readyState) { externalScript.onreadystatechange = function() { if (externalScript.readyState == "loaded" || externalScript.readyState == "complete") { externalScript.onreadystatechange = null; resolve(true); } }; } else { externalScript.onload = function() { resolve(true); }; } document.getElementsByTagName("head")[0].appendChild(externalScript); } catch(err) { reject(err); } } ); }}现在,在我的主要代码中,我可以执行以下操作,并确保在调用函数sayIt之前已加载该函数并准备使用。从异步函数内部:var loader = new loadIt();await loader.loadExternal();sayIt();从异步函数外部:var loader = new loadIt();(async function() { await loader.loadExternal();})().catch(err => { console.error(err);});sayIt();这很漂亮-正是我所追求的。谢谢,鲍勃!附带说明一下,我知道有一种猖and而短视的“在任何可以想象的情况下,阻止总是邪恶的,在任何情况下都永远不会带来任何好处”,但是我不同意阻止在正在生成一个由大量数据驱动的GUI,该GUI依赖于多个自定义类,而这些自定义类又相互依赖和/或依赖其他类/资源/脚本-尤其是在呈现的GUI元素具有多个事件处理程序时(,onclick,oninput等),它们期望这些类及其方法的实例的存在/可用性。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 如果您不能使用回调,请使用promises,后者旨在在异步环境中创建“阻止”机制,而无需添加单独的回调函数。 (adsbygoogle = window.adsbygoogle || []).push({});
10-01 21:39