当网页首次开始加载时,浏览器会下载图片,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
事件。您可以在其中获得响应的总长度和当前加载的内容。
以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
是可以跟踪进度的部分。