Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a JavaScript file in another JavaScript file [duplicate]

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?

like image 538
user1610950 Avatar asked Aug 26 '16 09:08

user1610950


People also ask

Can a JavaScript file load another JavaScript file?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

Should you have multiple JavaScript files?

You can write your JS in separate files, but when it comes to deploying, it's more efficient to minify them all into a single file. For each script you load in your browser, you make a round-trip to the server, so it makes sense to minimize those.

Can JavaScript be in a separate file?

You can keep the JavaScript code in a separate external file and then point to that file from your HTML document.


2 Answers

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

});
like image 158
Edison Biba Avatar answered Oct 16 '22 08:10

Edison Biba


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.

like image 27
Lulceltech Avatar answered Oct 16 '22 08:10

Lulceltech