判斷外部 JS 是否載入完成,一直是個跨瀏覽器的難題。傳統做法是用 IE 的 onreadystatechange 搭配其他瀏覽器的 onload,但 IE9/10 之後,情況悄悄改變了。
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>IE9/10同時支持script元素的onload和onreadystatechange事件</title> <script src="https://code.jquery.com/jquery.min.js" onload="alert(1)" onreadystatechange="alert(2)"></script> </head> <body> </body> </html>
IE6/7/8:彈出 2
IE9/10:彈出 2,1
Firefox/Safari/Chrome/Opera:彈出 1
由此可見,IE9 之後已經開始支援 script 的 onload 事件了。
長久以來,我們判斷 JS 是否載入完成,就是靠這兩個事件:IE 用 onreadystatechange,事件處理器裡用 readyState 判斷是否完成;其他瀏覽器則用 onload。
if(isIE){
script.onreadystatechange = function(){
if(this.readyState == 'loaded' || this.readyState == 'complete'){
callback();
}
}
}else{
script.onload = function(){
callback();
}
}
這種寫法至今仍然沒問題。
script.onload = script.onreadystatechange = function(){
if(!this.readyState || this.readyState == "loaded" || this.readyState == "complete"){
callback();
}
}
這種寫法的取巧之處在於讓 onload 與 onreadystatechange 共用同一個函式:Firefox/Safari/Chrome/Opera 不支援 onreadystatechange,也沒有 readyState 屬性,所以 !this.readyState 是針對這些瀏覽器;而 readyState 判斷則針對 IE,載入完畢時為 loaded,快取情況下可能出現 complete。兩個條件缺一不可。
但由於 IE9/10 也已支援 onload,這反而會造成 callback 在這些版本中執行兩次。因此,若要兼顧新舊 IE,仍需對版本做額外處理。
相關:
https://www.w3.org/TR/html401/interact/scripts.html#h-18.2.1
https://www.w3.org/TR/html5/scripting-1.html#script
https://developer.mozilla.org/En/HTML/Element/Script