使用jQuery AJAX加载多个脚本

时间:2016-09-16 17:53:01

标签: jquery ajax

如何使用jQuery AJAX加载多个脚本?

而不是:

jQuery(document).ready(function() {
    jQuery.ajax( { url: 'https://www.domaincom/js/script1.js', dataType: 'script' } );
    jQuery.ajax( { url: 'https://www.domaincom/js/script2.js', dataType: 'script' } );
});

更优雅,像这样:

jQuery(document).ready(function() {
    var scripts = [];
    scripts[0] = 'https://www.domaincom/js/script1.js';
    scripts[1] = 'https://www.domaincom/js/script2.js';

    jQuery.ajax( { url: scripts, dataType: 'script' } );
});

1 个答案:

答案 0 :(得分:0)

http://jsbin.com/moyijab/1/edit?js,output

let url = "https://rawgit.com/moongod101/c2682ecd0b52cdd631b45b94cbc18674/raw/6b3bdeda52f57aa3da0f8ec70eab54e406af76cf/jsbinAJAXScript.js";


let xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

            let back = xhttp.response;

            let scriptTag = document.createElement("script");
            scriptTag.innerHTML = back;
            document.querySelector("head").appendChild(scriptTag)


    }
  };
  xhttp.open("GET", url);
  xhttp.send();