我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?


当前回答

做一个小提问,并评估结果。

其他回答

请注意,我们通常使用静态脚本,所以我们希望尽可能多地从缓存中获取。

这节省了网络流量,加速着陆。

使用

$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
  console.log( textStatus );
});

存储:真实的选项已添加到 Ajax 方法。

也许这里还有另一种方式!

在 Node.js 中,你可以这样做,就像下面的代码一样!

主持人JS

    module.exports = {
      log: function(string) {
        if(console) console.log(string);
      }
      mylog: function(){
        console.log('just for log test!');
      }
    }

主.js

    const mylog = require('./sub');

    mylog.log('Hurray, it works! :)');
    mylog.mylog();

雷夫斯

HTTP://requirejs.org/docs/node.html

可以动态地创建一个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");

在后端,您可以使用 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);
var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);