1. 程式人生 > >js中 onreadystatechange 和 onload的區別

js中 onreadystatechange 和 onload的區別

chan creat code clas LG 參考 VR href ads

IE的script 元素只支持onreadystatechange事件,不支持onload事件。

FF的script 元素不支持onreadystatechange事件,只支持onload事件。

如果要在一個<script src="xx.js"> 加載完成執行一個操作,FF使用onload事件就行了,IE下則要結合onreadystatechange事件和this.readyState,

以下是IE的一個例子:
<script type="text/javascript" src="xx.xx" onreadstatechange="if(this.readyState==‘load‘) alert(‘loaded‘);"></script>

  

this.readyState的值為‘loaded‘或者‘complete‘都可以表示這個script已經加載完成.

如何結合IE和FF的區別?參考一下jquery的源碼:
var script = document.createElement(‘script‘);

script.src="xx.js";

script.onload = script.onreadystatechange = function(){

     if(  ! this.readyState     //這是FF的判斷語句,因為ff下沒有readyState這人值,IE的readyState肯定有值

          || this.readyState==‘loaded‘ || this.readyState==‘complete‘   // 這是IE的判斷語句

    ){

          alert(‘loaded‘);

    }

};

  

js中 onreadystatechange 和 onload的區別