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?

3
  • 1
    You can use webpack with require('otherfile.js'); Commented Aug 26, 2016 at 9: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..... Commented Sep 13, 2016 at 6:17
  • yes, use require Commented Aug 25, 2017 at 16:18

2 Answers 2

8

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

});
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.