js图片的预加载
1.
var
num=1;
var
list=[];
loadImage();
function
loadImage(){
var
img=
new
Image();
img.addEventListener(
"load"
,loadHandler);
img.src=
"./img/"
+num+
".jpg"
;
}
function
loadHandler(e){
list.push(
this
.cloneNode());
//复制当前图片元素
num++;
if
(num>100){console.log(list);
return
;}
this
.src=
"./img/"
+num+
".jpg"
;
//修改地址继续后触发load事件
}
2.
function
loadImage(src){
return
new
Promise(
function
(resolve,reject){
let img=
new
Image();
img.onload=
function
(){
resolve(img);
//加载时执行resolve函数
}
img.onerror=
function
(){
reject(src+
'这个地址错误'
);
//抛出异常时执行reject函数
}
img.src=src;
})
}
function
* fn(){
for
(let i=1;i<100;i++){
yield loadImage(
"./img/"
+i+
".jpg"
);
}
}
let s=fn();
let value=s.next().value;
resume();
function
resume(){
value.then(img=>{
console.log(img);
//打印加载的图片标签
value=s.next().value;
if
(value)resume();
});
}
3.
function
loadImage(src){
let p=
new
Promise(
function
(resolve,reject){
let img=
new
Image();
img.onload=
function
(){
//加载时执行resolve函数
resolve(img);
}
img.onerror=
function
(){
reject(src);
}
img.src=src;
})
return
p;
}
async
function
fn(){
let arr=[];
for
(let i=3;i<80;i++){
await loadImage(`./img/${i}-.jpg`).then(img=>{
arr.push(img);
});
}
return
arr;
}
fn().then(list=>{
console.log(list);
//打印图片数组
})