是否可以使网页加载元素按百分比进度?

时间:2019-04-29 14:44:31

标签: javascript dom

当网页首次开始加载时,浏览器将下载图像,javascript,CSS和其他资产。我想用(%)表示法来衡量加载进度。

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

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

window.onload = load;

window.onload 足以为网页创建一个简单的预加载器。在GitHub和Codepen中,有很多百分比的预加载器。但是他们没有计算绝对百分比,而是经过修改和静态的。如果我们可以衡量网页元素的加载进度,那么我们可以制作出令人敬畏且酷炫的预加载器

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

跟踪整个页面的进度可能会出现问题,但是可以跟踪特定资源。 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是可以跟踪进度的部分。