Using a javascript file in another js file

This question already has an answer here:

  • How do I include a JavaScript file in another JavaScript file? 51 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
    
    });
    

    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.

    链接地址: http://www.djcxy.com/p/42482.html

    上一篇: 如何知道JQuery是否完成加载

    下一篇: 在另一个js文件中使用JavaScript文件