學(xué)習(xí)自http://www.daqianduan.com/6419.html
單張圖片(圖片在文檔中)
// HTML
<img id='xiu' src="">
//js
$(document).ready(function(){
//jquery
$('#xiu').load(function(){
// 加載完成
});
//原生 onload
var xiu = document.getElementById('xiu')
xiu.onload = xiu.onreadystatechange = function(){
if(!this.readyState||this.readyState=='loaded'||this.readyState=='complete'){
// 加載完成
}
};
})
注:
1、IE8及以下版本不支持onload事件钻弄,但支持onreadystatechange事件佃却;
2、readyState是onreadystatechange事件的一個狀態(tài)窘俺,值為loaded或complete的時候饲帅,表示已經(jīng)加載完畢。
3瘤泪、以下內(nèi)容省略兼容
單張圖片(圖片動態(tài)創(chuàng)建)
//js
var xiu = new Image()
xiu.src = 'http://www.daqianduan.com/wp-content/uploads/2014/11/hs-xiu.jpg'
xiu.onload = function(){
// 加載完成
}
單張圖片(結(jié)合Promise)
//js
new Promise((resolve, reject)=>{
let xiu = new Image()
xiu.src = 'http://www.daqianduan.com/wp-content/uploads/2014/11/hs-xiu.jpg'
xiu.onload = function(){
// 加載完成
resolve(xiu)
}
}).then((xiu)=>{
//code
})
多張圖片
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 ){
//全部加載完成
}
}
}
多張圖片(結(jié)合Promise)
let 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'
];
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(){
//第i張加載完成
resolve(img[i])
}
})
}
Promise.all(promiseAll).then((img)=>{
//全部加載完成
})