簡體   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