动态加载JavaScript文件 [英] Dynamically load a JavaScript file
问题描述
如何可靠和动态地加载JavaScript文件?这可以用于实现一个模块或组件,当初始化组件将根据需要动态加载所有需要的JavaScript库脚本。
How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.
使用组件的客户端不需要加载所有库脚本文件(并手动插入< script>
标签到他们的网页),实现这个组件 - 只是'主'组件脚本文件。
The client that uses the component isn't required to load all the library script files (and manually insert <script>
tags into their web page) that implement this component - just the 'main' component script file.
主流JavaScript库如何完成此操作(Prototype,jQuery等)?这些工具将多个JavaScript文件合并为一个可再发行的'build'版本的脚本文件?或者他们是否进行任何动态加载的辅助库脚本?
How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)? Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file? Or do they do any dynamic loading of ancillary 'library' scripts?
除了这个问题:有一种方法来处理动态包含的事件加载了JavaScript文件?原型有文档范围事件的 document.observe
。示例:
An addition to this question: is there a way to handle the event after a dynamically included JavaScript file is loaded? Prototype has document.observe
for document-wide events. Example:
document.observe("dom:loaded", function() {
// initially hide all containers for tab content
$$('div.tabcontent').invoke('hide');
});
脚本元素的可用事件是什么?
推荐答案
You may write dynamic script tags (using Prototype):
new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});
这里的问题是,当外部脚本文件时,我们不知道完全加载。
The problem here is that we do not know when the external script file is fully loaded.
我们经常希望我们的依赖代码在下一行,并且喜欢写下如下:
We often want our dependant code on the very next line and like to write something like:
if (iNeedSomeMore) {
Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod();
myFancyMethod(); // cool, no need for callbacks!
}
有一种智能的方式来注入脚本依赖关系而不需要回调。你只需要通过一个同步的AJAX请求来提取脚本,并在全局层面上评估脚本。
There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level.
如果您使用Prototype,Script.load方法如下所示:
If you use Prototype the Script.load method looks like this:
var Script = {
_loadedScripts: [],
include: function(script) {
// include script only once
if (this._loadedScripts.include(script)) {
return false;
}
// request file synchronous
var code = new Ajax.Request(script, {
asynchronous: false,
method: "GET",
evalJS: false,
evalJSON: false
}).transport.responseText;
// eval code on global level
if (Prototype.Browser.IE) {
window.execScript(code);
} else if (Prototype.Browser.WebKit) {
$$("head").first().insert(Object.extend(
new Element("script", {
type: "text/javascript"
}), {
text: code
}
));
} else {
window.eval(code);
}
// remember included script
this._loadedScripts.push(script);
}
};
这篇关于动态加载JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!