如何在一个JavaScript文件中引用另一个JavaScript文件?

6283

如何在JavaScript文件中引用另一个JavaScript文件,类似CSS的@import


3
MDN JavaScript 模块文档,附带 github 上相应的例子 - djvg
我的回答在这里 https://dev59.com/43NA5IYBdhLWcg3wdtr5#72335692 被匿名地投了反对票,而且没有任何解释原因的评论,但我仍然强烈建议您查看它。 - aderchox
是的。这里的人有一种倾向,即对他们不喜欢或不理解的问题进行负面评价。 - luenib
71个回答

5406

JavaScript的旧版本没有import、include或require,因此已经开发了许多不同的方法来解决这个问题。

但是自2015年(ES6)以来,JavaScript拥有ES6模块标准来在Node.js中导入模块,这也得到了大多数现代浏览器的支持。

为了兼容旧版浏览器,可以使用像WebpackRollup这样的构建工具和/或像Babel这样的转译工具。

ES6模块

ECMAScript(ES6)模块从v8.5开始在Node.js中得到支持,需要使用--experimental-modules标志,在至少Node.js v13.8.0之后则不需要该标志。要启用"ESM"(与Node.js之前的CommonJS风格模块系统["CJS"]相对应),您可以在package.json中使用"type": "module"或将文件扩展名命名为.mjs。(类似地,使用Node.js之前的CJS模块编写的模块可以命名为.cjs,如果您的默认值为ESM,则可行。)

使用package.json

{
    "type": "module"
}

然后是 module.js

export function hello() {
  return "Hello";
}

然后,main.js
import { hello } from './module.js';
let val = hello();  // val is "Hello";

使用.mjs,你将拥有module.mjs

export function hello() {
  return "Hello";
}

然后是 main.mjs:
import { hello } from './module.mjs';
let val = hello();  // val is "Hello";

浏览器中的ECMAScript模块

自Safari 10.1、Chrome 61、Firefox 60和Edge 16起,浏览器直接支持加载ECMAScript模块(不需要像Webpack等工具)请在caniuse查看当前的支持情况。无需使用Node.js的.mjs扩展名,浏览器完全忽略模块/脚本文件扩展名。

<script type="module">
  import { hello } from './hello.mjs'; // Or the extension could be just `.js`
  hello('world');
</script>

// hello.mjs -- or the extension could be just `.js`
export function hello(text) {
  const div = document.createElement('div');
  div.textContent = `Hello ${text}`;
  document.body.appendChild(div);
}

请访问https://jakearchibald.com/2017/es-modules-in-browsers/了解更多内容。

浏览器中的动态导入

动态导入允许脚本在需要时加载其他脚本:

<script type="module">
  import('hello.mjs').then(module => {
      module.hello('world');
    });
</script>

请访问https://developers.google.com/web/updates/2017/11/dynamic-import了解更多信息。

Node.js require

旧的CJS模块风格在Node.js中仍被广泛使用,它是module.exports/require系统。

// mymodule.js
module.exports = {
   hello: function() {
      return "Hello";
   }
}

// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"   

JavaScript有其他方法可以在浏览器中包含外部JavaScript内容,而无需预处理。

AJAX加载

您可以使用AJAX调用加载附加脚本,然后使用eval运行它。这是最直接的方法,但由于JavaScript沙箱安全模型的限制,它仅限于您的域。使用eval还会带来错误、黑客和安全问题。

Fetch加载

像动态导入一样,您可以使用fetch调用和Fetch Inject库来加载一个或多个脚本,并使用承诺来控制脚本依赖项的执行顺序:

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

jQuery 加载

jQuery 库提供一行代码即可实现加载功能:

$.getScript("my_lovely_script.js", function() {
   alert("Script loaded but not necessarily executed.");
});

动态脚本加载

您可以将包含脚本 URL 的 script 标签添加到 HTML 中,这是避免使用 jQuery 的开销的理想解决方案。

脚本甚至可以驻留在不同的服务器上。此外,浏览器评估代码。script 标签可以注入到网页 head 或者插入到闭合的 body 标签前面。

以下是示例说明:

function dynamicallyLoadScript(url) {
    var script = document.createElement("script");  // create a script DOM node
    script.src = url;  // set its src to the provided URL
   
    document.head.appendChild(script);  // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}

这个函数将在页面头部添加一个新的<script>标签,其中src属性设置为作为第一个参数给出的URL。这两种解决方案都在JavaScript Madness: Dynamic Script Loading中讨论和说明。

检测脚本何时已被执行

现在,有一个你必须知道的大问题。这样做意味着你要远程加载代码。现代Web浏览器会异步加载文件并继续执行当前脚本,以提高性能。(这适用于jQuery方法和手动动态脚本加载方法。)
这意味着如果直接使用这些技巧,你将无法在要求加载后的下一行使用新加载的代码,因为它仍在加载中。
例如:my_lovely_script.js 包含 MySuperObject
var js = document.createElement("script");

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

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

然后你按下F5重新加载页面。它就可以工作了!有点令人困惑...

那么该怎么办呢?

好的,你可以使用我给你的链接中作者建议的hack方法。简而言之,对于急于解决问题的人,他使用一个事件来运行回调函数,当脚本被加载时会执行该事件。所以你可以将所有使用远程库的代码放在回调函数中。例如:

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.head;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

然后您需要在lambda函数中加载脚本之后编写要使用的代码:

var myPrettyCode = function() {
   // Here, do whatever you want
};

然后运行所有这些:
loadScript("my_lovely_script.js", myPrettyCode);

请注意,脚本可能在DOM加载之后或之前执行,这取决于浏览器以及是否包含了script.async = false;这一行。有一篇关于JavaScript加载的优秀文章讨论了这个问题。

源代码合并/预处理

正如本答案开头提到的那样,许多开发人员在他们的项目中使用构建/转译工具(如Parcel、Webpack或Babel),使他们能够使用即将推出的JavaScript语法,为旧版浏览器提供向后兼容性,组合文件,缩小文件大小,执行代码分割等操作。

我已经通过使用URL哈希,在单击菜单时动态加载了div,而不需要页面加载。我的问题是当我点击同一页2/3次后,js也会加载2/3次。这就是为什么每个事件发生多次的原因。 我想在将代码附加到页脚/头之前检查是否已经加载了js文件: var js = document.createElement("script");js.type = "text/javascript"; js.src = jsFilePath;document.body.appendChild(js); - Alien
你也可以使用类似 Gulp(https://gulpjs.com/)的工具对它们进行预处理,输出一个名为的单个文件。例如:a)将多个 JavaScript 文件合并成一个文件,b)使用 Babel 使其向后兼容,c)压缩/混淆以删除注释、空格等。然后,你不仅组织了这些文件,还通过启动一个管道来优化了它们,并有可能对其他文件格式(如 css 和图像)执行相同的操作。 - Steven Ventimiglia
使用“ECMAScript”方法时,我遇到了 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.hello.mjs更改为hello.js后问题得以解决。 - Dan

630

如果有人想要更高级的功能,可以尝试使用RequireJS。你将获得诸如依赖管理、更好的并发和避免重复(即多次检索脚本)等额外优点。

你可以将JavaScript文件编写为"模块",然后在其他脚本中引用它们作为依赖项。或者,你可以使用RequireJS作为一个简单的“获取此脚本”的解决方案。

示例:

将依赖项定义为模块:

some-dependency.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 文件,它依赖于 some-dependency.js

require(['some-dependency'], function(dependency) {

    //Your script goes here
    //some-dependency.js is fetched.   
    //Then your script is executed
});

来自GitHub自述文件的摘录:

RequireJS可以加载普通的JavaScript文件以及更具定义性的模块。它被优化用于在浏览器中使用,包括在Web Worker中使用,但也可以在其他JavaScript环境(如Rhino和Node)中使用。它实现了异步模块API。

RequireJS使用普通的脚本标记来加载模块/文件,因此应该易于调试。它可以简单地用于加载现有的JavaScript文件,所以你可以将其添加到现有项目中,而无需重写你的JavaScript文件。

...


238

实际上有一种方式可以加载JavaScript文件,而不是异步加载,因此您可以在加载后立即使用新加载的文件中包含的函数,并且我认为它适用于所有浏览器。

您需要在页面的<head>元素上使用jQuery.append(),也就是:

$("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错误控制台和Chrome开发者工具)将会错误地报告其位置,如果您经常使用Firebug来跟踪JavaScript错误(我是这样做的),那么这是一个大问题。由于某种原因,Firebug根本不知道新加载的文件,因此如果该文件中发生错误,则会报告错误发生在您的主要HTML文件中,您将难以找到错误的真正原因。

但如果这对您不是问题,那么这种方法应该可以解决。

实际上,我编写了一个名为$.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');

我为此还制作了一个简单的测试,网址是Example
在主HTML文件中包含了一个名为main.js的文件,然后main.js中的脚本使用$.import_js()导入了一个名为included.js的附加文件,该文件定义了这个函数:
function hello()
{
    alert("Hello world!");
}

在包含 included.js 后,立即调用了 hello() 函数,然后您会收到警报提示。
(这个回答是对 e-satis 评论的回应)。

176

我认为更加简洁的方法是,使用同步 Ajax 请求而不是使用 <script> 标签。这也是 Node.js 处理包含文件的方式。

以下是使用 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);
        }
    });
}

你可以像使用include一样在代码中使用它:

require("/scripts/subscript.js");

并能够在下一行调用所需脚本中的函数:

subscript.doSomethingCool(); 

130

可以从其他 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");

很好的回答。对于2015年及以上版本的浏览器,是否仍需要覆盖js.type?(即使回到Chrome 66,浏览器也没有任何问题理解服务器提供的MIME类型)。 - personal_cloud

112

好消息来了,很快你就可以轻松地加载 JavaScript 代码。它将成为导入 JavaScript 代码模块的标准方式,并且将成为核心 JavaScript 的一部分。

你只需编写 import cond from 'cond.js';,便可从文件 cond.js 中加载名为 cond 的宏。

因此,您无需依赖任何 JavaScript 框架,也不必明确地进行 Ajax 调用。

请参阅:


2
七年后,这个答案已经不再适用了:“SyntaxError: import declarations may only appear at top level of a module”。 - David Spector
分享你正在尝试做的代码。 - Imdad
好的,这里是运行良好的代码:function Include(jsFilePath) { var js = d.createElement("script"); js.type = "text/javascript"; js.src = jsFilePath; d.body.appendChild(js); } // Include - David Spector

91

声明 import 是在 ECMAScript 6 中出现的。

语法

import name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import name , { member [ , [...] ] } from "module-name";
import "module-name" as name;

69
也许你可以使用我在这个页面上找到的函数(如何在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)
}

61

这里是一个没有使用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);
}

请注意,要使其跨域工作,服务器需要在响应头中设置allow-origin标头。


53

我刚刚用 Prototype 编写了以下 JavaScript 代码,用于操作 DOM

var require = (function() {
    var _required = {};
    return (function(url, callback) {
        if (typeof url == 'object') {
            // We've (hopefully) got an array: time to chain!
            if (url.length > 1) {
                // Load the nth file as soon as everything up to the
                // n-1th one is done.
                require(url.slice(0, url.length - 1), function() {
                    require(url[url.length - 1], callback);
                });
            } else if (url.length == 1) {
                require(url[0], callback);
            }
            return;
        }
        if (typeof _required[url] == 'undefined') {
            // Haven't loaded this URL yet; gogogo!
            _required[url] = [];

            var script = new Element('script', {
                src: url,
                type: 'text/javascript'
            });
            script.observe('load', function() {
                console.log("script " + url + " loaded.");
                _required[url].each(function(cb) {
                    cb.call(); // TODO: does this execute in the right context?
                });
                _required[url] = true;
            });

            $$('head')[0].insert(script);
        } else if (typeof _required[url] == 'boolean') {
            // We already loaded the thing, so go ahead.
            if (callback) {
                callback.call();
            }
            return;
        }

        if (callback) {
            _required[url].push(callback);
        }
    });
})();

使用方法:

<script src="prototype.js"></script>
<script src="require.js"></script>
<script>
    require(['foo.js','bar.js'], function () {
        /* Use foo.js and bar.js here */
    });
</script>

总述:http://gist.github.com/284442.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接