博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Image Load Error Handler
阅读量:6399 次
发布时间:2019-06-23

本文共 3277 字,大约阅读时间需要 10 分钟。

Preface

In the past, I posted an answer in SO about how to . And the code is

window.addEventListener(  'error',  windowErrorCb,  {    capture: true  },  true)function windowErrorCb(event) {  let target = event.target  let isImg = target.tagName.toLowerCase() === 'img'  if (isImg) {    imgErrorCb()    return  }  function imgErrorCb() {    let isImgErrorHandled = target.hasAttribute('data-src-error')    if (!isImgErrorHandled) {      target.setAttribute('data-src-error', 'handled')      target.src = 'backup.png'    } else {      //anything you want to do      console.log(target.alt, 'both origin and backup image fail to load!')    }  }}

And the point is :

  1. Put the code in the head and executed as the first inline script. So, it will listen the errors happen after the script.
  2. Use event capturing to catch the errors earlier, also for those events which don't bubble.
  3. Use event delegation which avoids binding events on each image.
  4. Give the error img element an attribute after giving them a backup.png to avoid error of the backup.png and subsequent infinite loop like below:
img error->backup.png->error->backup.png->error->,,,,,

I thought the answer is almost perfect. But it turns out there is more scenes I don't know.

No Src?

Until Chrome 70.0.3538.102 in win7, code below wouldn't trigger error event.

But code below would trigger!

 

That does make sense. However, img without src wouldn't hidden. They would have 1px border like:

image

In this case, we may have to do something about that. For instance,

img:not([src]) {  opacity: 0;}

or a default backgroundImage which will work on img though 1px border is still there.

img:not([src]) {  background: no-repeat left top / cover;  background-image: linear-gradient(to right, lightblue, pink); /*or your logo*/}

BackgroundImage Error?

I still can't find a perfect solution for backgroundImage. The best answer in SO is like:

.app__bg_img_box {  background: no-repeat left top / cover;  background-image: url(./images/github.png), linear-gradient(to right, lightblue, pink);  /* you can also use default.png like code below */  /* background-image: url(./images/github.png), url(./images/default.png); */}

And the cons is obvious.

image

  1. You have to take care of the transparency problem of the target image.
  2. Users can see the toggle between target image and default image.
  3. A little flaw is that default image will always be downloaded.

Another way I figured out is like code below. Here is the simplest code:

let backgroundDivs = Array.from(document.querySelectorAll('.app__bg_img_box'))backgroundDivs.forEach(div => {  let imgUrl = window    .getComputedStyle(div)    .backgroundImage.match(/url\(["']?(.*)["']?\)/)  if (imgUrl) {    let img = new Image()    img.src = imgUrl[1]    img.onerror = function(event) {      div.style.backgroundImage = 'url(./images/default.png)'      img.onerror = null    }  }})

It will work well in most simple scenes but the cons is also obvious:

  1. Code will be more complicated if you want to deal with multiple backgroundImages.
  2. Each time you updated your dom structure, you may have to run the code above if you have add new divs with backgroundImage.

Ending

If lucky enough, we may have the new API in which would make code below work.

background: image('target.gif', 'fallback.gif');

Reference

转载地址:http://bhyea.baihongyu.com/

你可能感兴趣的文章
VMware虚拟化---集群高可用纵览
查看>>
Centos5上安装JRE和LUMAQQ
查看>>
Ping不通不代表主机不在线!
查看>>
SCCM2007安装部署指南
查看>>
关于监控工具的主动发起性能测试
查看>>
AngularJs $resource 高大上的数据交互
查看>>
Cisco基础实验回顾4--IP classless
查看>>
上接扩展GridView控件(6) - 响应行的单击事件和双击事件
查看>>
负载均衡实施 应该因地制宜
查看>>
非常好的BASH脚本编写教程
查看>>
MFC类库之CArray作为函数参数和返回值
查看>>
VMware vSphere 5.1 群集深入解析(十八)-DPM推荐向导&汇总
查看>>
plesk panel 虚拟主机管理平台 0day
查看>>
Java正则表达式进阶(一):写出常用的正则模式
查看>>
Android:Typeface、fonts、字体
查看>>
PgSQL · 源码分析 · AutoVacuum机制之autovacuum launcher
查看>>
MySQL初步使用
查看>>
【计算机网络】 DNS学习笔记 (>﹏<)
查看>>
ORA-01111: name for data file 119 is unknown - rename to correct file
查看>>
源代码构建Apache反向代理(包括SSL配置)
查看>>