为了用户体验更好,我们来实现一下图片的预加载
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()
}