js动态加载以及确定加载完成的代码

  1. 利用原生js动态加载js文件到页面,并在确定加载完成后调用相关function
    var otherJScipt = document.createElement("script"),
        otherJScipt.setAttribute("type", "text/javascript"),
        otherJScipt.setAttribute("src", "/xxx.js");
document.getElementsByTagName("head")[0].appendChild(otherJScipt); //追加到head标签内 


//判断服务器 
if (navigator.userAgent.indexOf("IE") >= 0) {
    //IE下的事件 
    otherJScipt.onreadystatechange = function() {
        //IE下的判断,判断是否加载完成 
        if (otherJScipt && (otherJScipt.readyState == "loaded" || otherJScipt.readyState == "complete")) {
            otherJScipt.onreadystatechange = null;
            callMyFun();
        }
    };
} else {
    otherJScipt.onload = function() {
        otherJScipt.onload = null;
        callMyFun();
    };
  1. jQuery内置了一个方法可以加载单一的js文件;当加载完成后你可以在回调函数里执行后续操作。最基本的使用jQuery.getScript的方法是这样
    jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) { 
     
        /*  
            做一些加载完成后需要执行的事情 
        */   
     
    }); 
    jQuery.getScript("/path/to/myscript.js") 
        .done(function() { 
            /* 耶,没有问题,这里可以干点什么 */ 
        }) 
        .fail(function() { 
            /* 靠,马上执行挽救操作 */ 
    }); 

     

posted @ 2015-04-22 15:29  Peter_zhou  阅读(1063)  评论(0编辑  收藏  举报