loading js files dynamically via another js file?

前端 未结 5 1872
慢半拍i
慢半拍i 2020-12-09 06:30

is there anyway to load other JS files from within a single JS file. I would like to point my individual pages \"ITS\" js file and that js file would load jquery, other js f

5条回答
  •  情深已故
    2020-12-09 07:20

    For external domain JS link

    var loadJs = function(jsPath) { 
        var s = document.createElement('script');
        s.setAttribute('type', 'text/javascript');
        s.setAttribute('src', jsPath);
        document.getElementsByTagName('head')[0].appendChild(s);
    };
    loadJs('http://other.com/other.js'); 
    

    For same domain JS link (Using jQuery)

    var getScript = function(jsPath, callback) {
        $.ajax({
            dataType:'script',
            async:false,
            cache:true,
            url:jsPath,
            success:function(response) {
                if (callback && typeof callback == 'function') callback();
            }
        });
    };
    getScript('js/other.js', function() { functionFromOther(); }); 
    

提交回复
热议问题