Home > Article > Web Front-end > How to Implement a Dynamic Progress Bar During Page Loading?
Display a Dynamic Progress Bar During Page Loading
The need for real-time feedback during loading screens has become increasingly important. Instead of a static image, let's explore how to implement a running progress bar that provides users with a visual representation of the loading process.
To implement a progress bar, we utilize the XMLHttpRequest (XHR) object's progress event. This event allows us to monitor both upload and download progress in real-time. Here's an example:
<code class="js">$.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 console.log(percentComplete); } }, false); // Download progress xhr.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; // Update the progress bar console.log(percentComplete); } }, false); return xhr; }, type: 'POST', url: "/", data: {}, success: function(data) { // Hide the progress bar after successful loading } });</code>
This script attaches event listeners to the XMLHttpRequest object, which trigger callbacks whenever upload or download progress occurs. Inside the callbacks, we calculate the percentage of completion and console log the value. This information can be used to dynamically update a progress bar, providing a visual cue to users about the status of the page loading process.
The above is the detailed content of How to Implement a Dynamic Progress Bar During Page Loading?. For more information, please follow other related articles on the PHP Chinese website!