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");
而且,这里没有“on error”情况:脚本将下载或不会(无论出于何种原因:不可用,连接性,服务器错误等)如果它[下载],当脚本正在执行/使用时可能发生的任何错误都不是真正的传输相关的(应该像对待任何其他脚本错误一样对待那些错误),因此您在这里使用“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错误,当你错过了一个大括号或由于其他语法错误而经常指向无关的位置。至少缺少一个括号是属于这个类别的,因为这样的语法错误实际上完全“转移”(某种类型)代码块,使得不可能弄清楚什么是什么。对不起,这里有点偏离主题。
http://stackoverflow.com/questions/4117712/add-script-tag-within-head-tag-in-servercontrol-asp-net – Neha 2012-02-09 09:44:10