為了用戶體驗(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()
}