如何在另一个JavaScript文件中包含一个JavaScript文件?

在JavaScript中是否有类似于CSS中@import的东西,可以让你在另一个JavaScript文件中包含一个JavaScript文件?

解决办法

旧版本的JavaScript没有import、include或require,所以针对这个问题开发了许多不同的方法。 但是从2015年(ES6)开始,JavaScript有了ES6模块标准,可以在Node.js中导入模块,大多数现代浏览器也支持这个标准。 为了与旧版浏览器兼容,可以使用build和/或transpilation工具。

ES6模块

Node.js从8.5版本开始支持ECMAScript(ES6)模块,使用--experimental-modules标志。所有涉及的文件必须有.mjs扩展名。

// module.mjs
export function hello() {
  return "Hello";
}
// main.mjs
import { hello } from 'module'; // or './module'
let val = hello();  // val is "Hello";

浏览器中的ECMAScript模块

浏览器已经支持直接加载ECMAScript模块(不需要Webpack等工具) Safari 10.1, Chrome 61, Firefox 60, 以及Edge 16.在caniuse查看当前的支持情况。

<script type="module">
  import { hello } from './hello.mjs';
  hello('world');
</script>
// hello.mjs
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

在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也为bug、黑客和安全问题打开了方便之门。

Fetch Loading

像动态导入一样,你可以通过一个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]1库提供了单行的加载功能。

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

动态脚本加载

你可以在HTML中添加一个带有脚本URL的脚本标签。为了避免jQuery的开销,这是一个理想的解决方案。 脚本甚至可以驻留在不同的服务器上。此外,浏览器会对代码进行评估。lt;script>标签可以被注入到网页的lt;head>中,或者插入到关闭的lt;/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:动态脚本加载》3中都有讨论和说明。

检测脚本何时被执行

现在,有一个你必须知道的大问题。这样做意味着你远程加载代码。现代的网络浏览器会加载文件并继续执行你当前的脚本,因为它们会异步加载一切以提高性能。(这同时适用于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。然后就成功了!令人困惑的是... **那么该怎么做呢? 好吧,你可以使用作者在我给你的链接中建议的破解方法。总之,对于急于求成的人来说,他用一个事件在脚本加载时运行一个回调函数。所以你可以把所有使用远程库的代码放在回调函数中。比如说

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加载后执行,也可能在DOM加载前执行,这取决于浏览器以及你是否包含了 "script.async = false; "这一行。有一篇[关于Javascript加载的伟大文章](http://www.html5rocks.com/en/tutorials/speed/script-loading/)讨论了这个问题

源代码合并/预处理

正如本答案顶部提到的,许多开发人员在他们的项目中使用Parcel、Webpack或Babel等构建/编译工具,允许他们使用新的JavaScript语法,为旧的浏览器提供向后的兼容性,合并文件,最小化,执行代码分割等。

评论(31)

它可以动态地生成一个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");
评论(13)

也许你可以使用我在这个页面上发现的这个功能如何在一个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)
}
评论(7)