要实现一个加载进度条功能,首先您需要了解 JavaScript 中的 XMLHttpRequest
和 onprogress
事件。
这个函数可以用来从 Web 服务器初始化和执行请求,onprogress
可以用来更新给定的 SPA (Single Page Application) 的进度条:
// Initialize the XMLHttpRequest Object.
var xhr = new XMLHttpRequest();
xhr.open("GET", "/my-data", true);
// Create a function that gets called when the state of the request changes.
xhr.onprogress = function(event){
// Calculate the progress percentage.
var percentComplete = (event.loaded / event.total) * 100;
// Update the progress bar with the new percentage.
document.getElementById("progressBar").value = percentComplete;
}
// When the request is completed, change the state of the progress bar.
xhr.onloadend = function(){
if(xhr.status == 200){
// If the request was successful, change color of the progress bar to green.
document.getElementById("progressBar").style.backgroundColor = "green"
}else{
// Otherwise, show an error.
console.log("There was an error loading the data.");
}
}
// Send the request.
xhr.send();
没有回复内容