JavaScript · 2024 年 6 月 7 日

动态加载js方法

function loadJs(url,callback){
    var head = document.getElementsByTagName('head')[0]; 
    var script= document.createElement("script"); 
    script.type = "text/javascript";
    script.src=url;
    head.appendChild(script);

    if(typeof(callback)!="undefined"){
        if(script.readyState){
            script.onreadystatechange=function(){
                if(script.readyState == "loaded" || script.readyState == "complete"){
                    script.onreadystatechange=null;
                    callback();
                }
            }
        }else{
            script.onload=function(){
                callback();
            }
        }
    }
}