javascript动态创建script,并监听onload、onerror
var oScript = document.createElement('script'); oScript.type = 'text/javascript'; oScript.src = "xx.js"; /* ** script标签的onload和onreadystatechange事件 ** IE6/7/8支持onreadystatechange事件 ** IE9/10支持onreadystatechange和onload事件 ** Firefox/Chrome/Opera支持onload事件 */ // 判断IE8及以下浏览器 var isIE = !-[1, ]; if (isIE) { oScript.onreadystatechange = function () {
//ie 即使404readyState也是loaded或complete if (this.readyState == 'loaded' || this.readyState == 'complete') { callback(); } } } else { // IE9及以上浏览器,Firefox,Chrome,Opera oScript.onload = function () { callback(); }
oScript.onerror = function () {
//error callback
}
}
var head = document.getElementsByTagName('head')[0];
head.appendChild(oScript);