推荐答案
// www.javascriptcn.com code example
function preloadImages(urls) {
return Promise.all(urls.map(url => {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = resolve;
img.onerror = reject;
});
}));
}
// 使用示例
const imageUrls = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg'
];
preloadImages(imageUrls)
.then(() => {
console.log('所有图片预加载完成');
})
.catch((error) => {
console.error('图片预加载失败:', error);
});本题详细解读
1. 函数功能
preloadImages 函数用于预加载多张图片。它接受一个包含图片 URL 的数组作为参数,并返回一个 Promise 对象。当所有图片都成功加载时,Promise 会被 resolve;如果其中任何一张图片加载失败,Promise 会被 reject。
2. 实现思路
- 遍历 URL 数组:使用
map方法遍历传入的图片 URL 数组,为每个 URL 创建一个Promise。 - 创建 Image 对象:对于每个 URL,创建一个新的
Image对象,并设置其src属性为当前 URL。 - 监听加载事件:通过
onload和onerror事件监听图片的加载状态。当图片加载成功时,resolve对应的Promise;当图片加载失败时,reject对应的Promise。 - 使用
Promise.all:将所有Promise放入Promise.all中,确保所有图片都加载完成或其中一张图片加载失败时,Promise.all会相应地resolve或reject。
3. 使用场景
- 图片预加载:在需要提前加载图片的场景中,如轮播图、图片画廊等,使用
preloadImages可以确保图片在需要显示时已经加载完成,避免用户看到空白或加载中的图片。 - 性能优化:通过预加载图片,可以减少用户在浏览页面时的等待时间,提升用户体验。
4. 注意事项
- 错误处理:在实际使用中,建议对
preloadImages的catch进行错误处理,以便在图片加载失败时能够及时发现问题并进行相应的处理。 - 跨域问题:如果图片资源来自不同的域名,可能会遇到跨域问题。确保服务器配置了正确的 CORS 策略,以避免加载失败。