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


当前回答

假设您想将 A.js 文件导入到 B.js 文件中。

现在肯定您已将 B.js 链接到 HTML 文件中,然后只需在 B.js 之前将 A.js 链接到 HTML 文件中。

这并不需要一个复杂的答案。

其他回答

您只能使用要求();标签。

例如,如果我有一个 addition.js 模块,我想添加到 math.js,我会这样做:

//this is math.js

//vars
let a = 1;
let b = 3;

//start of code
const additionfile = require('addition.js');
window.alert("You added " + a + " and " + b + " together, to get " + additionfile.add(a,b) + "!");

如果你想要添加.js 文件,它会看起来像这样的东西

function add(a,b) {
   const sum = a + b;
   return sum;
}

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

在现代语言中,如果脚本已经加载了,则会:

function loadJs( url ){
  return new Promise(( resolve, reject ) => {
    if (document.querySelector( `head > script[ src = "${url}" ]`) !== null ){
        console.warn( `script already loaded: ${url}` );
        resolve();
    }
    const script = document.createElement( "script" );
    script.src = url;
    script.onload = resolve;
    script.onerror = function( reason ){
        // This can be useful for your error-handling code
        reason.message = `error trying to load script ${url}`;
        reject( reason );
    };
    document.head.appendChild( script );
  });
}

使用(async/await):

try { await loadJs("https://.../script.js"); }
catch(error) { console.log(error); }

await loadJs( "https://.../script.js" ).catch( err => {} );

使用(承诺):

loadJs( "https://.../script.js" ).then( res => {} ).catch( err => {} );

我只是写了这个JavaScript代码(使用DOM操作的Prototype):

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.

var js = document.createElement("script");

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

document.body.appendChild(js);