繁体   English   中英

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

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

当网页首次开始加载时,浏览器会下载图片,javascript,CSS和其他资源。 我想用(%)符号来衡量这个加载进度。

为了做这个脚本,我已经探索了JavaScript的window.onload但是我没有得到任何所需的属性和方法。

function load() {
    var preload = document.querySelector('#magic-box');
    preload.style.display="none";
}

window.onload = load;

window.onload非常适合为网页创建一个简单的预加载器。 在GitHub和Codepen中有很多百分比预加载器。 但他们没有计算绝对百分比,他们被修改和静态。 如果我们可以测量网页元素加载进度,我们可以制作一个非常酷的预加载器

检查平均延迟,然后使用该时间加载百分比。 在此之后将状态设置为已加载

跟踪整个页面的进度可能会有问题,但可以跟踪跟踪特定资源。 xhr请求具有onprogress事件。 您可以在其中获得响应的总长度和当前加载的内容。

以此网站为例

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是可以跟踪进度的部分。

暂无
暂无

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

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