将图片的加载写成一个Promise,一旦加载完成,Promise的状态就发生变化。
const preloadImage = function (path) {
return new Promise(function (resolve, reject) {
var image = new Image();
image.onload = resolve;
image.onerror = reject;
image.src = path;
});
};
应用
// success
preloadImage("http://img2.37wanimg.com/2017/10/1219382866Qt8.jpg")
.then( () => {
console.log("success");
})
.catch( error => {
console.log( 'oh no', error );
});
success
// error
preloadImage("http://img2.37wanimg.com/2017/10/1219382866Qt.jpg")
.then( () => {
console.log("success");
})
.catch( error => {
console.log( 'oh no', error );
});
error
网友评论