我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
您只能使用要求();标签。
例如,如果我有一个 addition.js 模块,我想添加到 math.js,我会这样做:
//this is math.js
//vars
let a = 1;
let b = 3;
//start of code
const additionfile = require('addition.js');
window.alert("You added " + a + " and " + b + " together, to get " + additionfile.add(a,b) + "!");
如果你想要添加.js 文件,它会看起来像这样的东西
function add(a,b) {
const sum = a + b;
return sum;
}
其他回答
这就是简单的:
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
也许你可以使用我在此页面上发现的这个功能 如何将JavaScript文件纳入JavaScript文件中?
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
在后端,您可以使用 CommonJS 模块。
//a.js
function func () {
var result = "OK Bro";
return result;
}
module.exports = { func };
//b.js
var a = require('./a.js');
console.log(a.func);
您只能使用要求();标签。
例如,如果我有一个 addition.js 模块,我想添加到 math.js,我会这样做:
//this is math.js
//vars
let a = 1;
let b = 3;
//start of code
const additionfile = require('addition.js');
window.alert("You added " + a + " and " + b + " together, to get " + additionfile.add(a,b) + "!");
如果你想要添加.js 文件,它会看起来像这样的东西
function add(a,b) {
const sum = a + b;
return sum;
}
另一种方式,在我看来是更清洁的,是做一个同步的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();