利用VBScript 检测,有副作用,慎用!
var loadScript = function () {
var DOC = document,
HEAD = document.getElementsByTagName('head')[0];
// 往head注入一个script
var injectScript = function(src, beforeInject){
var script = document.createElement('script');
beforeInject.call(script);
script.src = src;
script.async = true;
HEAD.insertBefore(script, HEAD.firstChild);
return script;
};
// 销毁script标签
var destoryScript = function(script){
script.onerror = script.onreadystatechange = script.onload = null;
if (script.parentNode) {
script.parentNode.removeChild(script)
}
script = null;
};
return function(src, success, failure){
var dfd = $.Deferred();
if (DOC.dispatchEvent)
// 对于w3c标准浏览器,采用onerror和onload判断脚本加载情况
injectScript(src, function(){
var script = this;
script.onload = function(_, isAbort){
console.log(isAbort);
destoryScript(script);
// dfd.resolve();
};
script.onerror = function(_, isAbort){
destoryScript(script);
// dfd.reject();
};
});
else
// 对于恶心的IE8-,我们通过一个vbscript元素,来检测脚本是否加载成功
injectScript(src, function(){
var vbtest = this, flag = 0;
vbtest.language = 'vbscript';
var errorHandler = function(){
// 错误时,判断脚本是否正在解释,是则标志加载成功
if (vbtest.readyState == 'interactive') {
flag = 1;
}
return false;
};
window.attachEvent('onerror', errorHandler);
vbtest.onreadystatechange = function(_, isAbort){
if (/loaded|complete/.test(this.readyState)) {
// 标志位,当加载成功,置1;
if (flag == 1)
injectScript(src, function(){
var script = this;
script.onreadystatechange = function(){
if (/loaded|complete/.test(this.readyState)) {
destoryScript(script);
// dfd.resolve();
}
};
});
else {
// dfd.reject();
}
// 为window绑定一个错误,当js被误加载成vb的时候,会发生错误,来判断是否加载成功
window.detachEvent('onerror', errorHandler);
destoryScript(vbtest);
}
};
});
// 绑定成功失败
// if (typeof success == 'function') dfd.done(success);
// if (typeof failure == 'function') dfd.fail(failure);
// return dfd;
};
}();