Home >Web Front-end >CSS Tutorial >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>
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>
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!