动态加载js

function GetHttpRequest() {
            if (window.XMLHttpRequest) // Gecko 
                return new XMLHttpRequest();
            else if (window.ActiveXObject) // IE 
                return new ActiveXObject("MsXml2.XmlHttp");
        }
 
        function AjaxPage(url,callBack) {
            var oXmlHttp = GetHttpRequest();
 
            oXmlHttp.onreadystatechange = function() {
                if (oXmlHttp.readyState == 4) {
                    if (oXmlHttp.status == 200 || oXmlHttp.status == 304) {
                        document.getElementById("div_msg").innerHTML = document.getElementById("div_msg").innerHTML + ('得到js文本<br>');
                        createScript(oXmlHttp.responseText);
                        document.getElementById("div_msg").innerHTML = document.getElementById("div_msg").innerHTML + ('3秒后使用新的js<br>');
                        window.setTimeout(function() { callBack.call(); }, 3000);
                    }
                    else {
                        alert('XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')');
                    }
                }
            }
            oXmlHttp.open('GET', url, true);
            oXmlHttp.send(null);
//            oXmlHttp.open('POST', "handler1.ashx", true); 
//            oXmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  //ajax post请求比较给头信息加上这句。否则后台context.Request.Form访问不到
//            oXmlHttp.send("name=22222222222222");
        }
 
        function createScript(source) {
            if ((source != null)) {
                var oHead = document.getElementsByTagName('HEAD').item(0);
                var oScript = document.createElement("script");
                oScript.language = "javascript";
                oScript.type = "text/javascript";
                oScript.defer = true;
                oScript.text = source;
                oHead.appendChild(oScript);
            }
 
        }
 
        window.onload = function() {
            document.getElementById("div_msg").innerHTML = document.getElementById("div_msg").innerHTML + ('现在开始加载js<br>');
            AjaxPage("ganttchart/base_jjl.js", function() {
                document.getElementById("div_msg").innerHTML = document.getElementById("div_msg").innerHTML + ('完毕<br>');
                MyAlert("test");
            });
            
            
        } 
原文地址:https://www.cnblogs.com/jianjialin/p/1772990.html