// 定义 preloadImage 函数 const preloadImage = function (path) { return new Promise(function (resolve, reject) { const image = new Image(); image.onload = resolve; image.onerror = reject; image.src = path; }); }; // 使用 preloadImage 函数预加载图片 const imagePath = 'https://example.com/path/to/your/image.jpg'; preloadImage(imagePath) .then(function () { console.log('图片加载成功'); // 在这里可以执行一些操作,比如将图片显示在页面上 const imgElement = document.createElement('img'); imgElement.src = imagePath; document.body.appendChild(imgElement); }) .catch(function (error) { console.error('图片加载失败:', error); // 在这里可以处理图片加载失败的情况 });
Promise预加载图片
于 2024-11-18 14:58:21 首次发布