我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
如果有人正在寻找一些更先进的东西,试试 RequireJS. 你会得到添加的好处,如依赖管理,更好的竞争,并避免复制(即,获得一个脚本超过一次)。
您可以将 JavaScript 文件写入“模块”,然后将其列为其他脚本中的依赖,或者您可以使用 RequireJS 作为一个简单的“去获取这个脚本”解决方案。
例子:
将依赖定义为模块:
某些依赖性.js
define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) {
//Your actual script goes here.
//The dependent scripts will be fetched if necessary.
return libraryObject; //For example, jQuery object
});
implementation.js 是您的“主要” JavaScript 文件,取决于某些 dependency.js
require(['some-dependency'], function(dependency) {
//Your script goes here
//some-dependency.js is fetched.
//Then your script is executed
});
從 GitHub README 發表:
RequireJS 加载平面 JavaScript 文件以及更定义的模块. 它是优化在浏览器中的使用,包括在 Web 工作者,但它可以用于其他 JavaScript 环境,如 Rhino 和 Node. 它实施了 Asynchronous 模块 API. RequireJS 使用平面脚本标签加载模块/文件,所以它应该允许轻松的解体。
其他回答
我基本上做如下,创建一个新的元素,并添加它来主导:
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);
在 jQuery 中:
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// Script is now loaded and executed.
// Put your dependent JavaScript code here.
});
还有 Head.js. 很容易处理:
head.load("js/jquery.min.js",
"js/jquery.someplugin.js",
"js/jquery.someplugin.css", function() {
alert("Everything is ok!");
});
正如你所看到的,它比 Require.js 更容易,而且像 jQuery 的 $.getScript 方法一样方便,它还有一些先进的功能,如条件加载、功能检测等。
可以动态地创建一个JavaScript标签并将其添加到来自其他JavaScript代码的HTML文档中,这将加载针对JavaScript文件。
function includeJs(jsFilePath) {
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
}
includeJs("/path/to/some/file.js");
另一种方式,在我看来是更清洁的,是做一个同步的Ajax请求而不是使用一个<script>标签。
下面是使用 jQuery 的例子:
function require(script) {
$.ajax({
url: script,
dataType: "script",
async: false, // <-- This is the key
success: function () {
// all good...
},
error: function () {
throw new Error("Could not load script " + script);
}
});
}
然后你可以在你的代码中使用它,因为你通常会使用一个包括:
require("/scripts/subscript.js");
并能够在下列行中从所需脚本中呼叫一个函数:
subscript.doSomethingCool();
下面是没有jQuery的同步版本:
function myRequire( url ) {
var ajax = new XMLHttpRequest();
ajax.open( 'GET', url, false ); // <-- the 'false' makes it synchronous
ajax.onreadystatechange = function () {
var script = ajax.response || ajax.responseText;
if (ajax.readyState === 4) {
switch( ajax.status) {
case 200:
eval.apply( window, [script] );
console.log("script loaded: ", url);
break;
default:
console.log("ERROR: script not loaded: ", url);
}
}
};
ajax.send(null);
}
请注意,为了获得此工作跨域,服务器将需要在其响应中设置允许起源标题。