Home > Web Front-end > CSS Tutorial > How Can I Implement a Progress Bar During Page Loading with JavaScript?

How Can I Implement a Progress Bar During Page Loading with JavaScript?

DDD
Release: 2024-10-29 03:15:02
Original
650 people have browsed it

How Can I Implement a Progress Bar During Page Loading with JavaScript?

Displaying a Progress Bar During Page Loading

The need to display a progress bar while a page is loading can enhance user experience by providing visual feedback on the loading status. To create a running progress bar, one can leverage the Ajax event listeners to track the progress of any requests made to the server.

Here's a sample code that demonstrates how to implement this behavior:

<code class="javascript">$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        // Update the progress bar with the calculated percentage
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        // Update the progress bar with the calculated percentage
        console.log(percentComplete);
      }
    }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data) {
    //Do something success-ish
  }
});</code>
Copy after login

This code attaches event listeners to the XMLHttpRequest object, which initiates the Ajax request. The "progress" event is captured for both upload and download progress. Inside the event listeners, the percentage completion is calculated and can be used to update the progress bar UI accordingly.

For instance, if you have a progress bar element with an ID of "progress-bar," you could update its width using the computed percentage:

<code class="javascript">$("#progress-bar").css("width", percentComplete * 100 + "%");</code>
Copy after login

By incorporating this technique into your page loading process, users will be provided with a visual representation of the progress, enhancing the overall responsiveness and user experience of your application.

The above is the detailed content of How Can I Implement a Progress Bar During Page Loading with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template