老师,这里没有用Ajax封装吧,为什么要有load和error事件呢
相关代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>页面加载进度条</title>
<style>
html,
body,
.progress {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
}
img {
max-width: 100%;
}
.progress {
display: flex;
justify-content: center;
align-items: center;
}
.none {
display: none;
}
</style>
</head>
<body>
<div id="progress" class="progress">0%</div>
<div id="content" class="none"></div>
<script>
function wait(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
function loadImgAsync(url) {
return new Promise((resolve, reject) => {
const $img = new Image();
$img.addEventListener(
'load',
async () => {
// await wait(1000);
resolve($img);
},
false
);
$img.addEventListener(
'error',
() => {
reject(new Error('Could not load image at ' + url));
},
false
);
$img.src = url;
});
}
class Progress {
constructor($el) {
this.$el = $el;
}
update(done, total) {
this.$el.innerHTML = `${parseInt((done / total) * 100)}%`;
}
hide() {
this.$el.classList.add('none');
}
}
(async () => {
// const imgUrls = ['./ad.jpg', './ad_psyc.jpg', './logo.png'];
const imgUrls = [
'https://img1.mydrivers.com/Img/20100731/08213345.jpg',
'https://img1.mydrivers.com/Img/20100731/08230220.jpg',
'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg2.niutuku.com%2Fdesk%2F1208%2F2007%2Fntk-2007-25584.jpg&refer=http%3A%2F%2Fimg2.niutuku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1654222356&t=c1a0d60776a99882cc8e22192c4b12c1',
''
];
const total = imgUrls.length;
let done = 0;
const $content = document.getElementById('content');
const progress = new Progress(document.getElementById('progress'));
// 继发
// for (const url of imgUrls) {
// const $img = await loadImgAsync(url);
// // console.log($img);
// $content.appendChild($img);
// done++;
// progress.update(done, total);
// }
// await loadImgAsync(url);
// await loadImgAsync(url);
// await loadImgAsync(url);
// 并发
// 处理异步操作时,如果不存在继发关系,最好让它们并发执行
// async 函数内部是同步执行的,它本身是异步的
imgUrls.forEach(async url => {
try {
const $img = await loadImgAsync(url);
$content.appendChild($img);
done++;
progress.update(done, total);
} catch (error) {
console.log(error);
}
});
await wait(1000);
progress.hide();
$content.classList.remove('none');
})();
</script>
</body>
</html>9
收起
正在回答 回答被采纳积分+1
1回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星