When a web page starts loading for the first time browser download images, javascript, CSS and other assets. I want to measure this loading progress by (%) notations.
To do this script I have explored JavaScript's window.onload
but I didn't get any properties & methods as required.
function load() {
var preload = document.querySelector('#magic-box');
preload.style.display="none";
}
window.onload = load;
window.onload pretty enough for creating a simple preloader for the webpage. In the GitHub & Codepen there are a lot of percentage preloaders. But they are not calculating the absolute percent, They are modified & static. If we can measure webpages elements loading progress we can make an awsome & cool preloader
Check your average latency then use that time for loading percentage. After that time set your state to loaded
Tracking progress of entire page can be problematic, but tracking a specific resource can be tracked. An xhr request have onprogress
event. In which you can get total length of the response and currently loaded content.
As an example from this site
let xhr = new XMLHttpRequest();
// 2. Configure it: GET-request for the URL /article/.../load
xhr.open('GET', '/article/xmlhttprequest/example/load');
// 3. Send the request over the network
xhr.send();
// 4. This will be called after the response is received
xhr.onload = function() {
if (xhr.status != 200) { // analyze HTTP status of the response
alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
} else { // show the result
alert(`Done, got ${xhr.response.length} bytes`); // responseText is the server
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
console.log(`Received ${event.loaded} of ${event.total} bytes progress -> ${(event.loaded/event.total * 100)}%`);
} else {
console.log(`Received ${event.loaded} bytes`); // no Content-Length
}
};
xhr.onerror = function() {
alert("Request failed");
};
xhr.onprogress
is the part where progress can be tracked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.