js前端图片加载异常兜底方案


Posted in Javascript onJune 21, 2022

背景

网络环境总是多样且复杂的,一张图片可能会因为网路状况差而加载失败或加载超长时间,也可能因为权限不足或者资源不存在而加载失败,这些都会导致用户体验变差,所以我们需要一个图片加载异常的兜底方案。

<img>加载错误解决方案

内联事件

直接在img标签上使用内联事件处理图片加载失败的情况,但是这种方式代码侵入性太大,指不定就会有地方漏掉。

<img src='xxxxx' onerror="this.src = 'default.png'">

全局img添加事件

第一个方案侵入性太大,我们将入口收敛,为所有img标签统一添加error处理事件。

const imgs = document.getElementsByTagName('img')
Array.prototype.forEach.call(imgs, img =&gt; {
    img.addEventListener('error', e =&gt; {
        e.target.src = 'default.png'
    })
})

利用error事件捕获

为每个img添加事件处理函数的代价还是高了点,我们知道一般事件会经历三个阶段:

  • 捕获阶段
  • 处于目标阶段
  • 冒泡阶段

根据MDN文档中的描述:

When a resource (such as an <img> or <script>) fails to load, an error event using interface Event is fired at the element that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but can be handled with a EventTarget.addEventListener configured with useCapture set to true.

我们可以知道img和srcipt标签的error并不会冒泡,但是会经历捕获阶段和处于目标阶段。前两个方案就是利用处于目标阶段触发事件函数,这一次我们在捕获阶段截获并触发函数,从而减少性能损耗。

document.addEventListener(
    'error',
    e => {
        let target = e.target
        const tagName = target.tagName || ''
        if (tagName.toLowerCase = 'img') {
            target.src = 'default.png'
        }
        target = null
    },
    true
)

替换src方式的最优解

上面的方案有两个缺点:

  • 如果是因为网络差导致加载失败,那么加载默认图片的时候也极大概率会失败,于是会陷入无限循环。
  • 如果是网络波动导致的加载失败,那么图片可能重试就会加载成功。

所以我们可以为每个img标签额外添加一个data-retry-times计数属性,当重试超过限制次数后就用base64图片作为默认兜底。

document.addEventListener(
    'error',
    e => {
        let target = e.target
        const tagName = target.tagName || ''
        const curTimes = Number(target.dataset.retryTimes) || 0
        if (tagName.toLowerCase() === 'img') {
            if (curTimes >= 3) {
                target.src = 'data:image/png;base64,xxxxxx'
            } else {
                target.dataset.retryTimes = curTimes + 1
                target.src = target.src
            }
        }
        target = null
    },
    true
)

CSS处理的最优解

上面方式是采用替换src的方式来展示兜底图,这种解决方式有一个缺陷:

  • 原图的资源链接无法从标签上获取(虽然可以通过加data-xxx属性的方式hack解决)。

所以还有一种更好的方式,就是利用CSS伪元素::before和::after覆盖原本元素,直接展示兜底base64图片。

CSS样式如下:

img.error {
  display: inline-block;
  transform: scale(1);
  content: '';
  color: transparent;
}
img.error::before {
  content: '';
  position: absolute;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background: #f5f5f5 url(data:image/png;base64,xxxxxx) no-repeat center / 50% 50%;
}
img.error::after {
  content: attr(alt);
  position: absolute;
  left: 0; bottom: 0;
  width: 100%;
  line-height: 2;
  background-color: rgba(0,0,0,.5);
  color: white;
  font-size: 12px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

JS代码如下:

document.addEventListener(
    'error',
    e => {
        let target = e.target
        const tagName = target.tagName || ''
        const curTimes = Number(target.dataset.retryTimes) || 0
        if (tagName.toLowerCase() === 'img') {
            if (curTimes >= 3) {
                target.classList.remove('error')
                target.classList.add('error')
            } else {
                target.dataset.retryTimes = curTimes + 1
                target.src = target.src
            }
        }
        target = null
    },
    true
)

<img>加载超时解决方案

目前大多数应用都会接入CDN来加速资源请求,但是CDN存在节点覆盖不全的问题,导致DNS查询超时,此时如果切换Domain可能就会加载成功。

嗅探切换Domain(CNAME)

我们可以使用嗅探的方式,测试CDN提供的Domain是否能够正常访问,如果不行或者超时就及时切换成可访问Domain。 其中有几个注意点:

  • 为了防止嗅探图片缓存,需要添加时间戳保持新鲜度
  • Image图片加载没有超时机制,使用setTimeout模拟超时
// 防止嗅探图片存在缓存,添加时间戳保持新鲜度
export const imgUri = `/img/xxxxx?timestamp=${Date.now()}${Math.random()}`;

export const originDomain = 'https://sf6-xxxx.xxxx.com'

// 可采用配置下发的方式
export const cdnDomains = [
  'https://sf1-xxxx.xxxx.com',
  'https://sf3-xxxx.xxxx.com',
  'https://sf9-xxxx.xxxx.com',
];

export const validateImageUrl = (url: string) => {
  return new Promise<string>((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      resolve(url);
    };
    img.onerror = (e: string | Event) => {
      reject(e);
    };
    // promise的状态不可变性,使用setTimeout模拟超时
    const timer = setTimeout(() => {
      clearTimeout(timer);
      reject(new Error('Image Load Timeout'));
    }, 10000);
    img.src = url;
  });
};

export const setCDNDomain = () => {
  const cdnLoop = () => {
    return Promise.race(
      cdnDomains.map((domain: string) => validateImageUrl(domain + imgUri)),
    ).then(url => {
      window.shouldReplaceDomain = true;
      const urlHost = url.split('/')[2];
      window.replaceDomain = urlHost;
    });
  };

  return validateImageUrl(`${originDomain}${imgUri}`)
    .then(() => {
      window.shouldReplaceDomain = false;
      window.replaceDomain = '';
    })
    .catch(() => {
      return cdnLoop();
    });
};

// 替换URL
export const replaceImgDomain = (src: string) => {
  if (src && window.shouldReplaceDomain && window.replaceDomain) {
    return src.replace(originDomain.split('/')[2], window.replaceDomain);
  }
  return src;
};

服务端下发Domain(CNAME)

该方案需要后台同学配合,由后台判断当前当前可用Domain并返回。

getUsefulDomain()
    .then(e => {
        window.imgDomain = e.data.imgDomain || ''
    })

background-image加载异常解决方案

实际应用中背景图也会加载失败,通常这些元素没有error事件,所以也就无从捕获error事件了。此时就可以利用dispatchEvent,它同样拥有捕获阶段,MDN文档上是这么介绍的:

Dispatches an Event at the specified EventTarget, (synchronously) invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().

js前端图片加载异常兜底方案

可以看到支持度也还是可以的,我们首先需要自定义一个事件并初始化这个事件,在背景图加载失败的时候触发这个自定义事件,最后在上层捕获这个事件并执行事件函数。

自定义事件

自定义事件有两种方式:

  • 使用createEvent() 和 initEvent(),但是根据MDN文档,initEvent方法已经从浏览器标准中移除,并不安全,但支持度很高。

js前端图片加载异常兜底方案

  • 使用new Event()的方式,但是支持率稍微差一点

js前端图片加载异常兜底方案

这里以第二种为例,根据MDN文档的用法创建一个自定义事件:

const event = new Event('bgImgError')

嗅探加载情况

使用前面定义的方法嗅探图片资源的情况。

validateImageUrl('xxx.png')
    .catch(e => {
        let ele = document.getElementById('bg-img')
        if (ele) {
            ele.dispatchEvent('bgImgError')
        }
        ele = null
    })

添加事件捕获

document.addEventListener(
    'bgImgError',
    e => {
        e.target.style.backgroundImage = "url(data:image/png;base64,xxxxxx)"
    },
    true
)

以上就是js前端图片加载异常兜底方案的详细内容,更多关于js前端图片加载异常方案的资料请关注三水点靠木其它相关文章!


Tags in this post...

Javascript 相关文章推荐
告诉大家什么是JSON
Jun 10 Javascript
Jquery响应回车键直接提交表单操作代码
Jul 25 Javascript
js调用百度地图及调用百度地图的搜索功能
Sep 07 Javascript
js图片轮播特效代码分享
Sep 07 Javascript
初步了解javascript面向对象
Nov 09 Javascript
利用Node.js制作爬取大众点评的爬虫
Sep 22 Javascript
使用jQuery ajaxupload插件实现无刷新上传文件
Apr 23 jQuery
vue自定义指令directive实例详解
Jan 17 Javascript
Hexo已经看腻了,来手把手教你使用VuePress搭建个人博客
Apr 26 Javascript
页面点击小红心js实现代码
May 26 Javascript
Bootstrap的aria-label和aria-labelledby属性实例详解
Nov 02 Javascript
Vue使用路由钩子拦截器beforeEach和afterEach监听路由
Nov 16 Javascript
JavaScript中10个Reduce常用场景技巧
Jun 21 #Javascript
js前端面试常见浏览器缓存强缓存及协商缓存实例
Jun 21 #Javascript
JavaScript前端面试组合函数
Jun 21 #Javascript
Vue2项目中对百度地图的封装使用详解
JavaScript原型链中函数和对象的理解
JS精髓原型链继承及构造函数继承问题纠正
Jun 16 #Javascript
5个实用的JavaScript新特性
Jun 16 #Javascript
You might like
Discuz!5的PHP代码高亮显示插件(黑暗中的舞者更新)
2007/01/29 PHP
WordPress的文章自动添加关键词及关键词的SEO优化
2016/03/01 PHP
浅谈PHP eval()函数定义和用法
2016/06/21 PHP
使用PHP连接多种数据库的实现代码(mysql,access,sqlserver,Oracle)
2016/12/21 PHP
PHP实现微信小程序用户授权的工具类示例
2019/03/05 PHP
yii 框架实现按天,月,年,自定义时间段统计数据的方法分析
2020/04/04 PHP
PHP rsa加密解密算法原理解析
2020/12/09 PHP
jQuery 联动日历实现代码
2012/05/31 Javascript
js处理表格对table进行修饰
2014/05/26 Javascript
jQuery遍历之next()、nextAll()方法使用实例
2014/11/08 Javascript
js判断输入字符串是否为空、空格、null的方法总结
2016/06/14 Javascript
js手动播放图片实现图片轮播效果
2016/09/17 Javascript
详解vue路由篇(动态路由、路由嵌套)
2019/01/27 Javascript
vue使用Font Awesome的方法步骤
2019/02/26 Javascript
WebPack工具运行原理及入门教程
2020/12/02 Javascript
python 提取文件的小程序
2009/07/29 Python
python select.select模块通信全过程解析
2017/09/20 Python
Python 获取div标签中的文字实例
2018/12/20 Python
Python下利用BeautifulSoup解析HTML的实现
2020/01/17 Python
python GUI库图形界面开发之PyQt5滚动条控件QScrollBar详细使用方法与实例
2020/03/06 Python
python 通过邮件控制实现远程控制电脑操作
2020/03/16 Python
python Scrapy框架原理解析
2021/01/04 Python
CSS3 真的会替代 SCSS 吗
2021/03/09 HTML / CSS
HTML5 文件域+FileReader 分段读取文件并上传到服务器
2017/10/23 HTML / CSS
美国嘻哈首饰购物网站:Hip Hop Bling
2016/12/30 全球购物
佳能德国网上商店:Canon德国
2017/03/18 全球购物
联想台湾官网:Lenovo TW
2018/05/09 全球购物
ToysRus日本官网:玩具反斗城
2018/09/08 全球购物
绿色美容,有机护肤品和化妆品:Safe & Chic
2018/10/29 全球购物
幼师自荐信范文
2013/10/06 职场文书
电子信息工程自荐信
2014/05/26 职场文书
西安事变观后感
2015/06/12 职场文书
感恩教育观后感
2015/06/17 职场文书
如何利用js在两个html窗口间通信
2021/04/27 Javascript
JavaScript 与 TypeScript之间的联系
2021/11/27 Javascript
SQL Server数据库基本概念、组成、常用对象与约束
2022/03/20 SQL Server