var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "url to the script file here");
document.getElementsByTagName("head")[0].appendChild(script);
我之前用脚本寻找过“onload”,我不记得找到过这样的事件。我最终编写了一个基于计时器的 js 代码来经常检查预期在正在下载的脚本中定义的对象。所以,要么你这样做,要么:为什么不干脆不在插入脚本标签的代码中做任何事情——相反,当你的脚本准备好时,你有一个完美的时机:将“解包”代码添加到脚本本身(例如alert("I, the script, loaded and I'm ready with these functions that I provide");。
而且,这里没有“出错”的情况:脚本要么下载要么不下载(无论出于何种原因:不可用、连接性、服务器错误等)。如果确实 [下载],则在执行/使用该脚本时可能发生的任何错误都与传输无关(这些错误应以与处理任何其他脚本错误相同的方式处理),因此您的意图是“onerror “这里不合适(IMO)。 +1 :)
编辑:如果它没有下载,那么它就不会执行,你将无法使用它。如果您的客户端代码真的在等待,那么您将不得不编写某种基于计时器的超时逻辑;例如,在上面的“添加到标题”行之后,执行以下操作:
window.setTimeout(function()
{
// object/variable "newScriptObject" is defined in the new script
if(!newScript)
{
// script timed out; let's proceed with plan B
}
else
{
// script ready, proceed as planned;
// although, like I said, I think it's more precise if you execute this code in your myscript.js instead - as maybe that code will be ready before the 5 sec assumed here
// alternatively, use window.setInterval to check for objects defined this script every so milliseconds, in which case, when you find the script, don't forget to stop that timer (window.clearInterval)
}
}, 5000); // wait 5 sec for the new script
最后,在这种情况下没有“部分下载”之类的东西。一个理智的浏览器不会开始执行一个没有完全下载的脚本,不仅下载,而且解析(解释)。 “解释”部分是为什么当您在某处错过大括号或由于其他语法错误时,您会看到通常指向不相关位置的 JS 错误。至少缺少大括号属于这一类,因为这样的语法错误实际上会完全“转移”(某种)代码块,从而无法弄清楚是什么。抱歉,这里有点跑题了。