lxq.link

动态加载JS

ON THIS PAGE

方法一:直接在页面内document.write

document.write("<script src='test.js'><\/script>")

方法二:动态创建并添加script元素

function loadJs(url){
    var newScript = document.createElement("script")
    newScript.type = "text/javascript";
    newScript.src = url;
    document.body.appendChild(newScript)
}

方法二补充:添加回调函数

function loadJs(url,callback){
    var newScript = document.createElement("script")
    newScript.type = "text/javascript";
    newScript.src = url;
    document.body.appendChild(newScript)

    if(typeof(callback) != "undefined"){
        if (newScript.readyState) {
            newScript.onreadystatechange = function () {
                if (newScript.readyState == "loaded" || newScript.readyState == "complete") {
                    newScript.onreadystatechange = null;
                    callback();
                }
            };
        } else {
            newScript.onload = function () {
                callback();
            };
        }
    }
}
2019-05-15
上一篇:记录几个超级ping工具
下一篇:Installing Apache Maven