您可以编写动态脚本标签使用Prototype:
new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});这里的问题是我们不知道外部脚本文件何时完全加载。
我们经常希望我们的依赖代码在下一行,并且喜欢编写如下代码:
if (iNeedSomeMore) { script.load("myBigCodeLibrary.js"); // includes pre for myFancyMethod(); myFancyMethod(); // cool, no need for callbacks!}有一种聪明的方法可以注入脚本依赖项,而无需回调。您只需要通过 同步AJAX请求 提取脚本并在全局级别评估脚本。
如果您使用原型,则script.load方法如下所示:
var script = { _loadedscripts: [], include: function(script) { // include script only once if (this._loadedscripts.include(script)) { return false; } // request file synchronous var pre = new Ajax.Request(script, { asynchronous: false, method: "GET", evalJS: false, evalJSON: false }).transport.responseText; // eval pre on global level if (Prototype.Browser.IE) { window.execscript(pre); } else if (Prototype.Browser.WebKit) { $$("head").first().insert(Object.extend( new Element("script", { type: "text/javascript" }), { text: pre } )); } else { window.eval(pre); } // remember included script this._loadedscripts.push(script); }};


