原地址:??https://juejin.im/post/5d3e4304f265da1b8608cee5
個(gè)人覺(jué)得很有用處? 所以記錄在自己的博客里? 留有后用
JS監(jiān)聽(tīng)圖片的 error 事件
<img id="img" src="http://xxx.xxx.xxx/img.png">
let img = document.getElementById('img');
img.addEventListener('error',function(e){
? ? e.target.src = '//xxx.xxx.xxx/default.png'; // 為當(dāng)前圖片設(shè)定默認(rèn)圖
})
這樣不利于處理大量圖片的情況
內(nèi)聯(lián)方式監(jiān)聽(tīng)圖片的 error 事件
<img src="http://xxx.xxx.xxx/img.png" onerror="this.src = '//xxx.xxx.xxx/default.png'">
通過(guò)全局監(jiān)聽(tīng) error 事件
window.addEventListener('error',function(e){
? ? // 當(dāng)前異常是由圖片加載異常引起的
? ? if( e.target.tagName.toUpperCase() === 'IMG' ){
? ? ? ? e.target.src = '//xxx.xxx.xxx/default.jpg';
? ? }
},true)
當(dāng)網(wǎng)絡(luò)環(huán)境很差的時(shí)候 可以設(shè)置一個(gè)計(jì)數(shù)器? 當(dāng)達(dá)到期望次數(shù)? 改為提供一個(gè)Base64的圖片
window.addEventListener('error',function(e){
? ? let target = e.target, // 當(dāng)前dom節(jié)點(diǎn)
? ? ? ? tagName = target.tagName,
? ? ? ? times = Number(target.dataset.times) || 0, // 以失敗的次數(shù)啥纸,默認(rèn)為0
? ? ? ? allTimes = 3; // 總失敗次數(shù),此時(shí)設(shè)定為3
? ? // 當(dāng)前異常是由圖片加載異常引起的
? ? if( tagName.toUpperCase() === 'IMG' ){
? ? ? ? if(times >= allTimes){
? ? ? ? ? ? target.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
? ? ? ? }else{
? ? ? ? ? ? target.dataset.times = times + 1;
? ? ? ? ? ? target.src = '//xxx.xxx.xxx/default.jpg';
? ? ? ? }
? ? }
},true)