img.onload與script.onload實現的不一樣寫法

在http://www.cnblogs.com/outside/p/3714482.html中,如何使用img.onload已經很清楚,當使用一樣的方法建立script就有問題了html

var script = document.createElement("script");
script.src = "js/jquery.js";jquery

script.onload = function(){console.log("script")};app

這樣寫的話,本覺得能像img同樣,控制檯輸出script,但在firfox,ie(本次測試只在firfox,ie中測試)中均沒有輸出。dom

在網上搜索了一下,大概說ie使用的是onreadystatechange事件來監聽資源下載狀態的改變控制輸出,firfox使用onload事件控制資源下載完成後輸出。ide

如下代碼在ie中起做用測試

var script = document.createElement("script");
script.src = "js/jquery.js";
script.onreadystatechange = function(){
  if(this.readyState === "loaded" || this.readyState === "complete"){//ie7,8只認識complete
    alert("ie");
  }
}this

當onreadystatechange換成script.onload = function(){console.log("script")};來測試,卻沒有輸出,最後經過調試,發如今firfox中須要將script標籤添加到dom中去才能觸發事件(也即添加到dom中去纔開始下載),這點跟ie不一樣(ie跟script添加src就開始下載資源了)。url

最後在網上找了兩段兼容代碼,代碼以下調試

第一:htm

var url = "js/jquery.js";
var script = document.createElement("script");
if(script.addEventListener){
  script.addEventListener("load", callback, false);
}else if(script.attachEvent){
  script.attachEvent("onreadystatechange", function(){

    var target = window.event.srcElement;

     if(target.readyState == "loaded" || target.readyState == "complete"){

      callback.call(target);

    }

  });
}
document.getElementsByTagName("head")[0].appendChild(script);

function callback(){
console.log("兼容")
}
script.src=url;

第二:

var script = document.createElement("script");
script.onload = script.onreadystatechange = function(){
  if(!this.readyState || this.readyState=='loaded' || this.readyState=='complete'){
    func();
    script.onload = script.onreadystatechange = null;
  }
};
document.getElementsByTagName("head")[0].appendChild(script);
function func(){
  console.log("兼容")
}

script.src = "js/jquery.js";

相關文章
相關標籤/搜索