if(this.isie) {
js.onreadystatechange=function(){if(js.readystate==loaded || js.readystate==complete) callback();}
}else{js.onload=function(){callback();}}
js.onerror=function(){alert('not found (404): '+src)}//chrome
js判断脚本是否加载完成
在“按需加载”的需求中,我们经常会判断当脚本加载完成时,返回一个回调函数,那如何去判断脚本的加载完成呢?
我们可以对加载的 js 对象使用 onload 来判断(js.onload),此方法 firefox2、firefox3、safari3.1+、opera9.6+ 浏览器都能很好的支持,但 ie6、ie7 却不支持。曲线救国 —— ie6、ie7 我们可以使用 js.onreadystatechange 来跟踪每个状态变化的情况(一般为 loading 、loaded、interactive、complete),当返回状态为 loaded 或 complete 时,则表示加载完成,返回回调函数。
对于 readystate 状态需要一个补充说明:
在 interactive 状态下,用户可以参与互动。
opera 其实也支持 js.onreadystatechange,但他的状态和 ie 的有很大差别。
具体实现代码如下:
复制代码 代码如下:
function include_js(file) {
var _doc = document.getelementsbytagname('head')[0];
var js = document.createelement('script');
js.setattribute('type', 'text/javascript');
js.setattribute('src', file);
_doc.appendchild(js);
if (!/*@cc_on!@*/0) { //if not ie
//firefox2、firefox3、safari3.1+、opera9.6+ support js.onload
js.onload = function () {
alert('firefox2、firefox3、safari3.1+、opera9.6+ support js.onload');
}
} else {
//ie6、ie7 support js.onreadystatechange
js.onreadystatechange = function () {
if (js.readystate == 'loaded' || js.readystate == 'complete') {
alert('ie6、ie7 support js.onreadystatechange');
}
}
}
return false;
}
//execution function
include_js('http://www.jb51.net/jslib//jquery/jquery.js');