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


当前回答

若要在 JavaScript 中输入另一个脚本,请使用输入关键字:

import '/src/js/example.js';

// both types of quotes work
import "/src/js/example2.js";

其他回答

上面的功能工作顺利,如果您只加载一个脚本,或者您不关心多个脚本的加载顺序. 如果您有某些脚本依赖于其他,您需要使用承诺来指定加载顺序. 背后的原因是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插件。

设置一个名为“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>

但是:

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

你不能进口,但你可以参考。

PhpShtorm IDE. 要提到,在一个.js 文件到另一个.js,只需将此添加到文件的顶部:

<reference path="../js/file.js" />

当然,你应该使用自己的PATH到JavaScript文件。

我不知道它是否会在其他IDES中工作,也许是的,只是试试,它也应该在Visual Studio中工作。

我有一个简单的问题,但我被这个问题的答案震惊。

我不得不使用一个变量(myVar1)定义在一个JavaScript文件(myvariables.js)在另一个JavaScript文件(main.js)。

為此,我做了下面的:

在 HTML 文件中下载了 JavaScript 代码,在正确的顺序中, myvariables.js 首先,然后 main.js:

<html>
    <body onload="bodyReady();" >

        <script src="myvariables.js" > </script>
        <script src="main.js" > </script>

        <!-- Some other code -->
    </body>
</html>

文件: myvariables.js

var myVar1 = "I am variable from myvariables.js";

文件: main.js

// ...
function bodyReady() {
    // ...
    alert (myVar1);    // This shows "I am variable from myvariables.js", which I needed
    // ...
}
// ...

正如你所看到的,我在另一个JavaScript文件中使用了一个变量,但我不需要将一个添加到另一个文件中,我只需要确保第一个JavaScript文件在第二个JavaScript文件之前加载,并且,第一个JavaScript文件的变量在第二个JavaScript文件中可用,自动。

这拯救了我的日子,我希望这能帮助我。

我的常见方法是:

var require = function (src, cb) {
    cb = cb || function () {};

    var newScriptTag = document.createElement('script'),
        firstScriptTag = document.getElementsByTagName('script')[0];
    newScriptTag.src = src;
    newScriptTag.async = true;
    newScriptTag.onload = newScriptTag.onreadystatechange = function () {
        (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') && (cb());
    };
    firstScriptTag.parentNode.insertBefore(newScriptTag, firstScriptTag);
}

我尝试过AJAX方法(其他答案之一),但它似乎对我来说并不那么好。

这里解释了代码如何为那些有趣的人工作:基本上,它创建了一个新的脚本标签(之后的第一个)的URL. 它将其设置为无同步模式,所以它不会阻止其余的代码,但在准备状态(需要加载的内容的状态)变更为“加载”时召回。