Using a JavaScript file in another JavaScript file

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.


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

});