21

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 .js files say one for addition, subtraction, multiplication, division, etc..

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

Is that possible?

informatik01
  • 16,038
  • 10
  • 74
  • 104
user1610950
  • 1,837
  • 5
  • 33
  • 49
  • 1
    You can use webpack with `require('otherfile.js');` – jcubic Aug 26 '16 at 09:09
  • it really seems like js is not suitable for my current project. I had to drop javascript and move to another programming language. I though over the intervening time since that original question js would've modernized a bit. Who wants a monolithic file, especially with js async code execution, name collisions, etc... sure i could wrap up functions and make them anon but wow..... – user1610950 Sep 13 '16 at 06:17
  • yes, use require – Brian Ruchiadi Aug 25 '17 at 16:18

2 Answers2

7

Using javascript:

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

Using jQuery:

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

});
Edison Biba
  • 4,384
  • 3
  • 17
  • 33
1

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.

Lulceltech
  • 1,662
  • 11
  • 22