目前有一个需求是批量预加载大量图片,我用了new Image去循环加载,然后需要执行一个方法,但是现在没有好的方法判断
现在写的,部分无关代码去掉了,怎么确定each内的Image全部加载过了呢,新手还望赐教:
var photo = function() {
var photoKey = [];
var avatarKey = [];
var errorKey = [];
var showKey = [];
var tempHtml = '';
//Get image data
this.getImg = function () {
$.post('...', { company_id:'...' }, function (data) {
if(data !== 'fail'){
$.each(data, function(i,n){
//insert Name
insert(n.id, n.nickname, 'name');
//Photo load
var photo = new Image();
photo.src = n.photo;
photo.onload = function (){
insert(n.id, n.photo, 'photo');
photoKey.push(n.id);
};
photo.onerror = function (){
errorKey.push(n.id);
};
//Avatar load
var avatar = new Image();
avatar.src = n.avatar;
avatar.onload = function (){
insert(n.id, n.avatar, 'avatar');
avatarKey.push(n.id);
};
avatar.onerror = function (){
errorKey.push(n.id);
}
});
}else {
alert('预加载失败');
}
},'json');
};
//Store to local
var insert = function (id, data, type) {
if(type == 'photo' && data !== ""){
//console.log('%c存储照片\n'+id+'\npath:'+data, "color:#007fff");
localStorage['prePhoto'+id] = data
}else if(type == 'avatar' && data !== ""){
//console.log('%c存储头像\n'+id+'\npath:'+data, "color:#007fff");
localStorage['preAvatar'+id] = data
}else if(type == 'name'){
localStorage['preName'+id] = data
}
};
//Check if key is repeated
var checkKey = function (){
console.log('checkKey');
$.each(photoKey, function(i,n){
if($.inArray(n, avatarKey) !== -1){
showKey.push(n);
}
});
};
};
根据您的要求,给您提三个解决办法:
办法一
办法二
办法三