进度条方案
程序员文章站
2022-06-16 08:21:30
...
说起用户体验,不得不提到进度条,加载页面时给用户提供一个实时的进度显示将大大降低页面加载过慢导致的用户流失,这次总结下几个常见的进度条实现方案。
- 定时器加载loading.gif,大概估算页面加载时间,隐藏loading;
- 一开始显示loading.gif,页面加载完成时隐藏loading.gif
/* 文档状态document.readyState: loading:加载html阶段,尚未完成解析时 interactive:html文档解析完成,加载外部资源阶段时 complete:加载完成时 */ var loading = document.getElementById('loading'); document.onreadystatechange = function(){ if(document.readyState === 'complete'){ loading.style.display = 'none'; } }
// 测试显示执行顺序为onreadystatechange -> onready -> DOMContentLoaded -> onload
window.onload = function(){ console.log(document.readyState '(onload)'); } document.addEventListener('DOMContentLoaded', function(){ console.log(document.readyState '(DOMContentLoaded)'); }) document.onready = function(){ console.log(document.readyState '(onready)'); } document.onreadystatechange = function(){ console.log(document.readyState '(onreadystatechange)'); } - css实现loading动画
/* 新的属性要加上浏览器前缀 */ <style> .loading{ width: 100%;height: 100%;position: fixed;top: 0;left: 0;z-index: 100;background: #fff; } .pic{ width: 60px;height: 60px;position: absolute;top: 0;bottom: 0;left: 0;right: 0;margin: auto; } i{ display: block;float:left;width: 6px;height: 60px;background: #399;margin: 0 2px;transform: scaleY(0.4);animation: load 1.3s infinite; } i:nth-child(2){animation-delay: 0.1s;} i:nth-child(3){animation-delay: 0.2s;} i:nth-child(4){animation-delay: 0.3s;} i:nth-child(5){animation-delay: 0.4s;} @keyframes load{ 0%,40%,100%{transform: scaleY(0.4)} 20%{transform: scaleY(1)} } </style><div class='loading'> <div class='pic'> <i></i> <i></i> <i></i> <i></i> <i></i> </div> </div>
- 顶部loading进度条:
可以将 ’ <script>改变顶部进度宽度</script> ’ 插入html文档中,利用文档从上到下的执行顺序来显示进度条效果; - 根据实时数据显示百分比进度(由于网页加载缓慢的原因大多是图片过多过大导致,所以实时数据可由图片加载情况计算得出);
<style> .loading{ width: 100%;height: 100%;position: fixed;top: 0;left: 0;z-index: 100;background: #fff; } .pic{ width: 100px;height: 100px;line-height: 100px;position: absolute;top: 0;bottom: 0;left: 0;right: 0;margin: auto;border:1px solid ccc;text-align: center; } span{ display: block;width: 80px;height: 80px;position:absolute;top: 10px;left: 10px;box-shadow: 0 30px 0 #666;border-radius: 50%;animation: rotate 1s infinite linear; } @keyframes rotate{ 0%{transform: rotate(0 deg)}; 100%{transform: rotate(360deg)}; } </style> <div class='loading'> <div class='pic'> <span></span> <b>%</b> </div> </div> <img src='' /> <img src='' /> <script> $(function(){ var img = $('img'); var num = 0; img.each(function(i){ var oImg = new Image(); oImg.onload = function(){ oImg.onload = null; num ; $('b').html(parseInt(num/$('img').size()*100) '%'); if(num >= i){ $('.loading').fadeOut(); } }; oImg.src = img[i].src; }); }) </script>
更多专业前端知识,请上【猿2048】www.mk2048.com