当前位置:首页 > JavaScript

js实现加载进度条

2026-01-30 16:26:01JavaScript

使用XMLHttpRequest监听进度事件

通过XMLHttpRequest对象的progress事件可以获取文件加载进度。创建一个进度条div,根据事件中的loadedtotal属性更新进度条宽度:

const xhr = new XMLHttpRequest();
const progressBar = document.getElementById('progress-bar');

xhr.open('GET', 'large-file.url', true);
xhr.onprogress = (e) => {
  if (e.lengthComputable) {
    const percent = (e.loaded / e.total) * 100;
    progressBar.style.width = `${percent}%`;
  }
};
xhr.send();

使用Fetch API配合ReadableStream

Fetch API结合ReadableStream可以实现更现代的进度监控方案。通过读取响应体的流数据计算进度:

js实现加载进度条

fetch('large-file.url')
  .then(response => {
    const reader = response.body.getReader();
    const contentLength = +response.headers.get('Content-Length');
    let received = 0;

    return new ReadableStream({
      start(controller) {
        function push() {
          reader.read().then(({done, value}) => {
            if (done) {
              controller.close();
              return;
            }
            received += value.length;
            const percent = (received / contentLength) * 100;
            updateProgressBar(percent);
            controller.enqueue(value);
            push();
          });
        }
        push();
      }
    });
  });

页面加载进度模拟

对于页面整体加载进度,可以结合DOM事件模拟进度效果。监听DOMContentLoadedload事件分阶段更新进度:

window.addEventListener('DOMContentLoaded', () => {
  updateProgress(70); // 模拟DOM加载完成70%
});

window.addEventListener('load', () => {
  updateProgress(100); // 页面完全加载
});

function updateProgress(percent) {
  document.querySelector('.progress-bar').style.width = `${percent}%`;
}

CSS动画作为后备方案

当无法获取真实加载进度时,可以使用CSS动画创建无限循环的进度条效果:

js实现加载进度条

.progress-bar {
  animation: progress 2s ease-in-out infinite;
  background: linear-gradient(to right, #4cd964, #5ac8fa);
}

@keyframes progress {
  0% { width: 0%; }
  100% { width: 100%; }
}

分段加载进度计算

对于多资源加载场景,需要跟踪每个资源的加载状态。维护一个加载队列,计算总体进度:

const resources = ['a.jpg', 'b.js', 'c.css'];
let loadedCount = 0;

resources.forEach(url => {
  fetch(url).then(() => {
    loadedCount++;
    const percent = (loadedCount / resources.length) * 100;
    updateProgressBar(percent);
  });
});

进度条UI组件实现

创建可复用的进度条组件,包含动画和状态管理功能:

class ProgressBar {
  constructor(selector) {
    this.element = document.querySelector(selector);
    this.value = 0;
  }

  setValue(percent) {
    this.value = Math.min(100, Math.max(0, percent));
    this.element.style.width = `${this.value}%`;
  }

  complete() {
    this.setValue(100);
    setTimeout(() => this.element.style.opacity = 0, 500);
  }
}

标签: 进度条加载
分享给朋友:

相关文章

php实现进度条

php实现进度条

PHP 实现进度条的方法 使用 HTML 和 CSS 结合 PHP 实现进度条 在 PHP 中,进度条通常通过 HTML 和 CSS 实现,PHP 负责计算进度并更新前端显示。 <di…

vue实现图片加载

vue实现图片加载

Vue 实现图片加载的方法 在 Vue 中实现图片加载可以通过多种方式,以下是一些常见的方法: 使用 v-bind 绑定图片路径 通过 v-bind 动态绑定图片路径,可以灵活地加载本地或远程图片…

js实现图片加载

js实现图片加载

使用Image对象加载图片 通过JavaScript的Image对象可以动态加载图片,适用于需要预加载或动态插入图片的场景。 const img = new Image(); img.src…

vue实现加载更多

vue实现加载更多

Vue 实现加载更多功能 在 Vue 中实现加载更多功能通常涉及监听滚动事件或点击按钮触发加载更多数据。以下是几种常见的实现方式: 滚动监听实现无限滚动 通过监听滚动事件,当用户滚动到页面底部时自…

vue懒加载实现方案

vue懒加载实现方案

vue懒加载实现方案 路由懒加载 使用动态导入语法实现路由级别的懒加载,适用于Vue Router配置。通过import()函数返回Promise,Webpack会自动分割代码块。 const ro…

vue实现滚动鼠标加载

vue实现滚动鼠标加载

vue实现滚动鼠标加载的实现方法 使用Intersection Observer API Intersection Observer API可以监听元素是否进入视口,适合实现滚动加载。在Vue中可以通…