【问题标题】:Is it possible to get web-page loading elements progress in percentage?是否可以按百分比获取网页加载元素的进度?
【发布时间】:2019-04-30 21:34:42
【问题描述】:

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

要执行此脚本,我已经探索了 JavaScript 的 window.onload,但没有获得所需的任何属性和方法。

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

window.onload = load;

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

【问题讨论】:

  • 据我所知这是做不到的,因为浏览器在开始下载时不知道资源有多大。您可以预先计算资源的大小,然后对其进行硬编码。否则你只能计算一个估计值。也许performance api 可以帮助你。如果您使用 xhr 请求或使用 fetch() 预加载新页面,则完全有可能

标签: javascript dom


【解决方案1】:

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

this网站为例

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

【讨论】:

    【解决方案2】:

    检查您的平均延迟时间,然后将该时间用于加载百分比。在那之后将你的状态设置为加载

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 2012-05-20
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2012-05-24
      • 2010-12-29
      • 1970-01-01
      • 2014-10-12
      相关资源
      最近更新 更多