0

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

Tanmoy Biswas
  • 171
  • 1
  • 1
  • 17
  • 1
    As far as I know this can't be done, since the browser does not know how big a ressource is when it starts downloading it. You could precalculate the size of the ressources and then hard code them. Otherwise you can only calculate an estimate. Maybe the [performance api](https://developer.mozilla.org/en-US/docs/Web/API/Performance) can help you. If you preload the new page with an xhr request or using fetch() then it is completely possible – Wendelin Apr 29 '19 at 15:21
  • Possible duplicate of [How to show a running progress bar while page is loading](https://stackoverflow.com/questions/18981909/how-to-show-a-running-progress-bar-while-page-is-loading) – Towkir Apr 30 '19 at 06:24

2 Answers2

1

Check your average latency then use that time for loading percentage. After that time set your state to loaded

1

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.

Mitul
  • 108
  • 2
  • 10