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


当前回答

有一个好消息给你. 很快你将能够轻松地加载JavaScript代码. 它将成为进口JavaScript代码的标准方式,并将是核心JavaScript本身的一部分。

您只需要从“cond.js”中输入代码;从“cond.js”文件中加载一个名为 macro 的代码。

因此,您不需要依靠任何JavaScript框架,也不需要明确进行Ajax通话。

提到:

静态模块分辨率模块充电器

其他回答

是的,有......

在 ES6 中,我们可以将部分或整个JavaScript文件导出并导入到另一个文件中。

但等待,ES6不支持所有浏览器,所以你需要通过 babel.js 使用它,例如...

所以你创建一个类如下:

class Person {
  constructor(name) {
    this.name = name;
  }

  build() {
    return new Person(this);
  }
}

module.exports = Person;

import { Person } from 'Person';

您也可以要求文件如:

const Person = require('./Person');

如果您正在使用更古老的 JavaScript 版本,您可以使用 requirejs:

requirejs(["helper/util"], function(util) {
    // This function is called when scripts/helper/util.js is loaded.
    // If util.js calls define(), then this function is not fired until
    // util's dependencies have loaded, and the util argument will hold
    // the module value for "helper/util".
});

如果你想坚持旧版本的物品,如jQuery,你也可以使用一些东西,如 getScript:

jQuery.getScript('./another-script.js', function() {
    // Call back after another-script loaded
});

最后,但不要忘记,你可以用 <script> 标签一起编写脚本的传统方式。

<script src="./first-script.js"></script>
<script src="./second-script.js"></script>
<script src="./third-script.js"></script>

注意: 有几种方式可以执行一个外部脚本: 如果 async 存在: 脚本与页面剩余的同步执行(脚本将执行,而页面继续播放) 如果 async 没有存在,并且 defer 存在: 脚本在页面完成播放时执行 如果没有 async 或 defer 存在: 脚本被捕并执行 imme

我来到这个问题,因为我正在寻找一个简单的方式来保持一个收藏有用的JavaScript插件。

设置一个名为“plugins.js”的文件(或 extensions.js 或任何你想要的)。 保持你的插件文件与一个主文件。

//set array to be updated when we add or remove plugin files
var pluginNames = ["lettering", "fittext", "butterjam", etc.];

//one script tag for each plugin
$.each(pluginNames, function(){
    $('head').append('<script src="js/plugins/' + this + '.js"></script>');
});

手动呼叫你的头中的一个文件: <script src="js/plugins/plugins.js"></script>

但是:

雖然所有插件都落入頭標籤的方式,他們不總是通過瀏覽器,當你點擊到頁面或更新。

这里是一个基本插件,允许您使用 @import “path/to/file.js”; syntax 在任何文件中,包括JavaScript文件。

它可以通过 npm 安装安装: https://npmjs.org/package/grunt-import

$("head").append($("<script></script>").attr("src", url));

/* Note that following line of code is incorrect because it doesn't escape the
 * HTML attribute src correctly and will fail if `url` contains special characters:
 * $("head").append('<script src="' + url + '"></script>');
 */

但是,这个方法也有一个问题:如果一个错误发生在进口的JavaScript文件,Firebug(以及Firefox Error Console和Chrome Developer Tools也)将报告其位置错误,这是一个很大的问题,如果你使用Firebug跟踪JavaScript错误很多(我做)。

但是,如果这不是一个问题,那么这个方法应该工作。

我實際上寫了一個名為 $.import_js() 的 jQuery 插件,使用此方法:

(function($)
{
    /*
     * $.import_js() helper (for JavaScript importing within JavaScript code).
     */
    var import_js_imported = [];
    
    $.extend(true,
    {
        import_js : function(script)
        {
            var found = false;
            for (var i = 0; i < import_js_imported.length; i++)
                if (import_js_imported[i] == script) {
                    found = true;
                    break;
                }
            
            if (found == false) {
                $("head").append($('<script></script').attr('src', script));
                import_js_imported.push(script);
            }
        }
    });
    
})(jQuery);

因此,所有你需要做才能进口JavaScript是:

$.import_js('/path_to_project/scripts/somefunctions.js');

我也做了一个简单的测试为这个例子。

它包含主.js 文件在主 HTML 中,然后在主.js 中的脚本使用 $.import_js() 来导入一个名为 included.js 的额外文件,该文件定义了此功能:

function hello()
{
    alert("Hello world!");
}

(这个答案是回复e-satis的评论)。

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