前端实现图片预加载

为了用户体验更好,我们来实现一下图片的预加载

const images = [
  'http://location:3000/image1.jpg',
  'http://location:3000/image2.jpg',
  'http://location:3000/image3.jpg',
  'http://location:3000/image4.jpg',
  'http://location:3000/image5.jpg',
  'http://location:3000/image6.jpg',
  'http://location:3000/image7.jpg',
  'http://location:3000/image8.jpg',
  'http://location:3000/image9.jpg',
]

export async function loadImage() {
  const  _images = [...images]
  const src = _images.shift()
  return new Promise((resolve,reject) => {
    const link = document.createElement('link')
    link.rel = 'proload'
    link.as = 'image'
    link.href = src
    document.head.appendChild(link)
    link.onload = resolve
    link.onerror = reject
    // 模拟超时,10s后如果图片还没有加载完成,就会reject
    setTimeout(reject,10000)
  })
}
//因为浏览器的并发请求有限制,只能一次性加载6个,所以我们不能一次性加载所有的图片,而是需要分批加载。
// 预加载3次
//递归调用loadImage函数加载图片,直到所有图片加载完毕
function _loadImage() {
  loadImage().finally(()=>{
    if(images.length) {
      _loadImage()
    }
  })
}
for(let i = 0;i < 3;i++) {
  _loadImage()
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容