课程名称:await 函数用法
课程章节:页面加载进度条
课程讲师: Alex
课程内容:
页面加载进度条
对于一些需要加载大量图片的网站,刚打开可能只是一张空白页面,然后才是图片的慢慢加载,这种用户体验比较糟糕
所以,我们可以给这个网站做一个加载进度条,在图片加载完成之前只显示加载进度条,每完成一张图片的加载,进度条就往前走一点,直到所有的图片都加载完毕,进度条显示100%,进度条消失,内容才显示出来
这样可以在一定程度上提升用户体验,效果:
进度条:progress 内容;content 先是隐藏起来的,等进度条展示100%,进度条隐藏,隐藏的方式:在content上加 none
<div id="progress" class="progress">0%</div> <div id="content" class="none"></div>
样式:
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; }
<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>
今天学习到此为止,加油