HTML資源標籤onerror屬性
阿新 • • 發佈:2018-11-22
測試程式碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <script> alert('first'); function alertError(thisObject){ var outerHTML = thisObject.outerHTML; // 這個就是出錯的物件的標籤,這樣資源載入失敗是不是就可以記錄通過一些手段記錄到伺服器了!!! alert('script-error'); } </script> <body > <img class="currentImg" id="currentImg" onerror="alert('img-error')" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523532560732&di=f4440f7230c3ac36bd87c4cb0534d56d&imgtype=0&src=http%3A%2F%2Fc.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2F35a85edf8db1cb1353fd8b78de54564e93584bc0.jpg"/> </body> <script onerror="javascript:alertError(this)" src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> <script> window.onload = function(e){ alert('global onload'); } </script> </html>
結果(測試結果不一致時請清除瀏覽器快取):
1、輸出依次是 “first”、“global onload”,說明載入第一個<script>標籤後其中的程式碼得到執行,這就是為什麼alertError函式必須寫在程式碼開頭!
2、若將<script>中src改成錯誤的src(或故意斷網),則alertError函式會被觸發,實參this指代的是該標籤對應的DOM
3、<img>標籤同理,利用this物件可以把該標籤中的onerror函式改為 onerror="javascript:this.src='./backup.img'",這樣資源圖片找不到時就有了備份圖片。
測試環境:Chrome瀏覽器