上传下载进度事实上是使用到了xmlhttprequset对象中的progress事件。
对于下载,可在xhr.onprogress上做监听。
对于上传,可在xhr.upload.onprogress上做监听。
监听事件要在xhr.open(method,url)前进行绑定。
为了保证正确执行,必须在调用 open()之前添加 onprogress 事件处理程序。–《JavaScript高级程序指南v4》
究其原因,可能是由于,xhr.open实现的功能是定义本次请求,xhr.send仅仅是将定义好的请求发出去,如果在定义请求后的同步代码中添加onprogress处理程序会导致无法正确监听到事件进度。
效果图
在进度条移动的部分加上了transition动画,在progress上做了节流,防止进度条变化过快。
进度条主要代码(事件监听)
// 主要代码
function ajax(url, method = 'GET', data = null) {
return new Promise((res, rej) => {
let tag = 0; // tag用于节流
let xhr = new XMLHttpRequest();
xhr.onload = function () {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
res(xhr.responseText);
} else {
rej(`err with ` + xhr.status);
}
}
let type = data ? 'upload' : 'load';
if (type === 'load') {
xhr