js实现加载进度条
实现基础进度条
使用HTML和CSS创建一个简单的进度条结构,通过JavaScript动态更新宽度:
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
</div>
.progress-container {
width: 100%;
height: 5px;
background-color: #f0f0f0;
}
.progress-bar {
height: 100%;
width: 0%;
background-color: #4CAF50;
transition: width 0.3s ease;
}
const progressBar = document.getElementById('progressBar');
let progress = 0;
function updateProgress() {
progress += 5;
progressBar.style.width = progress + '%';
if(progress < 100) {
setTimeout(updateProgress, 200);
}
}
updateProgress();
模拟真实加载进度
对于文件加载或资源请求,可以使用XMLHttpRequest的progress事件:

function loadFile(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onprogress = function(e) {
if(e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
progressBar.style.width = percent + '%';
}
};
xhr.onload = function() {
progressBar.style.width = '100%';
};
xhr.send();
}
loadFile('large-file.pdf');
使用Fetch API实现
现代JavaScript可以使用Fetch API配合ReadableStream实现进度跟踪:
async function fetchWithProgress(url) {
const response = await fetch(url);
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
while(true) {
const {done, value} = await reader.read();
if(done) break;
receivedLength += value.length;
const percent = (receivedLength / contentLength) * 100;
progressBar.style.width = percent + '%';
}
}
fetchWithProgress('large-data.json');
平滑动画效果
添加CSS过渡效果使进度变化更平滑:

.progress-bar {
transition: width 0.5s cubic-bezier(0.4, 0.0, 0.2, 1);
}
完整页面加载进度
监听页面整体加载进度:
document.addEventListener('DOMContentLoaded', () => {
progressBar.style.width = '50%';
});
window.addEventListener('load', () => {
progressBar.style.width = '100%';
setTimeout(() => {
progressBar.style.opacity = '0';
}, 500);
});
进度条颜色变化
根据进度百分比改变颜色:
function updateColor(percent) {
if(percent < 30) {
progressBar.style.backgroundColor = '#ff5252';
} else if(percent < 70) {
progressBar.style.backgroundColor = '#ffab40';
} else {
progressBar.style.backgroundColor = '#4CAF50';
}
}
这些方法可以根据实际需求组合使用,创建出符合项目要求的加载进度指示效果。






