1、单张图片(图片动态生成)
//js var xiu = new Image() xiu.src = 'http://static.igeekee.cn/scenelogo/default.png' xiu.onload = function(){ // 加载完成 }
2、单张图片(结合ES6 Promise)
new Promise((resolve, reject)=>{ let xiu = new Image() xiu.src = 'http://static.igeekee.cn/scenelogo/7tianliansuo.jpg' xiu.onload = function(){ // 加载完成 resolve(xiu) } }).then((xiu)=>{ // code console.log(xiu) })
3、多张图片(js)
var img = [], flag = 0, mulitImg = [ 'http://www.daqianduan.com/wp-content/uploads/2017/03/IMG_0119.jpg', 'http://www.daqianduan.com/wp-content/uploads/2017/01/1.jpg', 'http://www.daqianduan.com/wp-content/uploads/2015/11/jquery.jpg', 'http://www.daqianduan.com/wp-content/uploads/2015/10/maid.jpg' ]; var imgTotal = mulitImg.length; for(var i = 0 ; i < imgTotal ; i++){ img[i] = new Image() img[i].src = mulitImg[i] img[i].onload = function(){ //第i张图片加载完成 flag++ if( flag == imgTotal ){ //全部加载完成 } } }
4、多张图片(结合ES6 Promise.all())
let mulitImg = [ 'http://static.igeekee.cn/scenelogo/zhongguoyinhang.png', 'http://static1.igeekee.cn/2_1487751969296_2872.jpg', 'http://static1.igeekee.cn/25_1488621623561_6152.jpg', 'http://static.igeekee.cn/scenelogo/pizzahut.png' ]; let promiseAll = [], img = [], imgTotal = mulitImg.length; for(let i = 0;i < imgTotal; i++) { promiseAll[i] = new Promise((resolve,reject)=>{ img[i] = new Image() img[i].src = mulitImg[i] img[i].onload=function(){ resolve(img[i]) } }) } Promise.all(promiseAll).then((img)=>{ console.log('加载完成') })