在另一个 JavaScript 文件中使用 JavaScript 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39162449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:17:37  来源:igfitidea点击:

Using a JavaScript file in another JavaScript file

javascriptimport

提问by user1610950

I am writing some JavaScript files that will not be used with HTML documents. For example, writing a calculator in one JavaScript file, where I'll have different .jsfiles say one for addition, subtraction, multiplication, division, etc..

我正在编写一些不会与 HTML 文档一起使用的 JavaScript 文件。例如,在一个 JavaScript 文件中编写一个计算器,其中我将有不同的.js文件,例如加法、减法、乘法、除法等。

I'd like to have each math operation in a self contained .jsfile then have another .jsfile that will #include the other smaller files and can call the functions from them?

我想在一个自包含.js文件中包含每个数学运算,然后有另一个.js文件,该文件将#include 其他较小的文件并可以从它们调用函数?

Is that possible?

那可能吗?

采纳答案by Edison Biba

Using javascript:

使用javascript:

var script = document.createElement('script');
script.src = '/js/script';
document.head.appendChild(script);

Using jQuery:

使用jQuery:

//you need to change your path
$.getScript('/js/script.js', function()
{
    // script is imported

});

回答by Lulceltech

Here is a synchronous version:

这是一个同步版本:

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);
}

Note that to get this working cross-domain, the server will need to set allow-origin header in its response.

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