判断脚本,图片,CSS,iframe等是否加载完成

1.图片

<img id="MyImg" src="src"/>
jquery实现
$("#MyImg").load(function(){
})
说明:在jquery中load方法是在对象加载完毕后触发

javascript实现:

JS判断img图片是否加载完成:使用onload或者onreadystatechange

function   isImgLoad(){
    if(!!window.ActiveXObject){  // IE
        if(img.readyState == 'complete'){
            alert('finished');
        }
        else{
            alert('loading');
        }
    }
    else{
        // 非IE
        if(img.complete == true){
            alert('finished');
        }
        else{
            alert('loading');
        }
    }
}   

2.动态加载js,css文件

 

 function loadjscssfile(filename,filetype){

    if(filetype == "js"){        

       var fileref = document.createElement('script');        

       fileref.setAttribute("type","text/javascript");       

  fileref.setAttribute("src",filename);    

}else if(filetype == "css"){         

  var fileref = document.createElement('link');        

fileref.setAttribute("rel","stylesheet");       

  fileref.setAttribute("type","text/css");       

  fileref.setAttribute("href",filename);    

}   

if(typeof fileref != "undefined"){        

document.getElementsByTagName("head")[0].appendChild(fileref);   

  }  

   }

loadjscssfile("do.js","js");

loadjscssfile("test.css","css");

3.判断iframe是否加载完成

var iframe = document.createElement("iframe");

iframe.src = "http://www.jb51.net";

if (!/*@cc_on!@*/0) { //if not IE

iframe.onload = function(){

alert("Local iframe is now loaded.");

};

} else {

iframe.onreadystatechange = function(){

if (iframe.readyState == "complete"){

alert("Local iframe is now loaded.");

}

};

}

document.body.appendChild(iframe);

或者:

var iframe = document.createElement("iframe");

iframe.src = "http://www.jb51.net";

if (iframe.attachEvent){

iframe.attachEvent("onload", function(){

alert("Local iframe is now loaded.");

});

} else {

iframe.onload = function(){

alert("Local iframe is now loaded.");

};

}

document.body.appendChild(iframe);

 

 

 

 

 

posted @ 2013-09-29 17:51  hlp鹏  阅读(588)  评论(0编辑  收藏  举报