前端實(shí)現(xiàn)圖片預(yù)加載

為了用戶體驗(yàn)更好,我們來(lái)實(shí)現(xiàn)一下圖片的預(yù)加載

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
    // 模擬超時(shí),10s后如果圖片還沒(méi)有加載完成,就會(huì)reject
    setTimeout(reject,10000)
  })
}
//因?yàn)闉g覽器的并發(fā)請(qǐng)求有限制,只能一次性加載6個(gè),所以我們不能一次性加載所有的圖片,而是需要分批加載。
// 預(yù)加載3次
//遞歸調(diào)用loadImage函數(shù)加載圖片,直到所有圖片加載完畢
function _loadImage() {
  loadImage().finally(()=>{
    if(images.length) {
      _loadImage()
    }
  })
}
for(let i = 0;i < 3;i++) {
  _loadImage()
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容