判断脚本是否加载完成的方法
在“按需加载”的需求中,我们经常会需要判断脚本是否加载完成,此判断方法在firefox和ie下有所不同

firefox下用onload 来判断,ie下用onreadystatechange 来跟踪每个状态变化的情况(一般为 loading 、loaded、interactive、complete),当返回状态为 loaded 或 complete 时,则表示加载完成

示例代码:

//创建script节点
var _doc = document.getElementsByTagName('head')[0];    
var js = document.createElement('script');    
js.setAttribute('type', 'text/javascript');    
js.setAttribute('src', file);    
_doc.appendChild(js);

//添加状态判断
if(firefox){
js.onload = function () {
alert('Firefox');
}
}else if(ie){
js.onreadystatechange = function () {            
if (js.readyState == 'loaded' || js.readyState == 'complete') {                
alert('IE6、IE7 support js.onreadystatechange');            
}        
}
}
irini   2009-04-14 10:07:17 评论:0   阅读:193   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2008 powered by YuLog