简体   繁体   English

是否有可能使网页加载元素的百分比进步?

[英]Is it possible to get web-page loading elements progress in percentage?

When a web page starts loading for the first time browser download images, javascript, CSS and other assets. 当网页首次开始加载时,浏览器会下载图片,javascript,CSS和其他资源。 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. 为了做这个脚本,我已经探索了JavaScript的window.onload但是我没有得到任何所需的属性和方法。

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. window.onload非常适合为网页创建一个简单的预加载器。 In the GitHub & Codepen there are a lot of percentage preloaders. 在GitHub和Codepen中有很多百分比预加载器。 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. xhr请求具有onprogress事件。 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. xhr.onprogress是可以跟踪进度的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM