利用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; }; }();