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


当前回答

下面是使用HTML导入的浏览器(而不是Node.js)。

首先,所有 JavaScript 类和脚本都不是.js 文件,而是.js.html 文件(.js.html 只是在 HTML 页面和完整的 JavaScript 脚本/类之间识别),在 <script> 标签中,如下:

MyClass.js.html 的内容:

<script>
   class MyClass {

      // Your code here..

   }

</script>

然后,如果你想进口你的班级,你只需要使用HTML进口:

<link rel="import" href="relative/path/to/MyClass.js.html"/>

<script>
   var myClass = new MyClass();
   // Your code here..
</script>

此分類上一篇: HTML 輸入將減少

HTML 进口减少,有利于 ES6 模块,您应该使用 ES6 模块。

其他回答

上面的功能工作顺利,如果您只加载一个脚本,或者您不关心多个脚本的加载顺序. 如果您有某些脚本依赖于其他,您需要使用承诺来指定加载顺序. 背后的原因是JavaScript加载资源如脚本和图像无同步。

因此,这里是另一个动态LoadScript的版本,保证下载命令:

// Based on: https://javascript.info/promise-basics#example-loadscript
function dynamicallyLoadScript(url) {
  return new Promise(function(resolve, reject) {
    var script = document.createElement("script");
    script.src = url;
    script.onload = resolve;
    script.onerror = () => reject(new Error(`Error when loading ${url}!`));
    document.body.appendChild(script);
  });
}

dynamicallyLoadScript("script1.js")
  .then(() => dynamicallyLoadScript("script2.js"))
  .then(() => dynamicallyLoadScript("script3.js"))
  .then(() => dynamicallyLoadScript("script4.js"))
  .then(() => dynamicallyLoadScript("script5.js"))
//...

现在,脚本按 script1.js、 script2.js、 script3.js 等顺序加载。

dynamicallyLoadScript("script1.js")
  .then(() => dynamicallyLoadScript("script2.js"))
  .then(() => foo()) // foo can be a function defined in either script1, script2
  .then(() => dynamicallyLoadScript("script3.js"))
  .then(() => {
     if (var1){ // var1 can be a global variable defined in either script1, script2, or script3
          bar(var1); // bar can be a function defined in either script1, script2, or script3
     } else {
          foo(var1);
     }
  })
//more .then chains...

要显示未经处理的承诺拒绝(错误加载脚本等),将此未经处理的拒绝事件听器放在代码的顶部:

// Based on: https://javascript.info/promise-error-handling#unhandled-rejections
window.addEventListener('unhandledrejection', function(event) {
  // the event object has two special properties:
  console.error(event.promise);// the promise that generated the error
  console.error(event.reason); // the unhandled error object
});


短短功能

function dynamicallyLoadScripts(urls) {
  if (urls.length === 0)
    return;

  let promise = dynamicallyLoadScript(urls[0]);
  urls.slice(1).forEach(url => {
    promise = promise.then(() => dynamicallyLoadScript(url));
  });
}

要使用它,只需通过一系列脚本URL如下:

const scriptURLs = ["dist/script1.js", "dist/script2.js", "dist/script3.js"];
dynamicallyLoadScripts(scriptURLs);

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

从丹·达斯卡莱斯库(Dan Dascalescu)的答案,从Facebook的想法中获取了一些图书馆的扩展。

(function() {
var __ = {};
this._ = function(name, callback) {
    if(__[name]==undefined) {
        __[name] = true;
        var firstScript = document.getElementsByTagName('script')[0],
          js = document.createElement('script');
          js.src =  name;
          js.onload = callback;
          firstScript.parentNode.insertBefore(js, firstScript);
    }
}
})();

(new _('https://cdnjs.cloudflare.com/ajax/libs/Snowstorm/20131208/snowstorm-min.js', function() {
 snowStorm.snowColor = '#99ccff';
}));

如果您正在使用 Web 工作者,并希望在工作者的范围内添加额外的脚本,则其他关于添加脚本到标签标签等的答案不会为您工作。

幸运的是,网页工作者有自己的 importScripts 功能,这是在网页工作者的范围内的全球功能,原生于浏览器本身,因为它是规格的一部分。

否则,因为第二个最高的投票答案突出你的问题,RequireJS也可以处理包括在WebWorker内部的脚本(可能称之为ImportScripts本身,但有几个其他有用的功能)。

您也可以使用 PHP 编写脚本:

文件 main.js.php:

<?php
    header('Content-type:text/javascript; charset=utf-8');
    include_once("foo.js.php");
    include_once("bar.js.php");
?>

// Main JavaScript code goes here