XMLHttpRequest:loadstart 事件
基線 廣泛可用
此功能非常成熟,可在許多裝置和瀏覽器版本中使用。自 2015 年 7 月.
報告反饋
注意: 此功能在 Web Workers 中可用,但 Service Workers 除外。
語法
loadstart 事件在請求開始載入資料時觸發。
在諸如
addEventListener() 之類的 方法中使用事件名稱,或設定事件處理程式屬性。addEventListener("loadstart", (event) => {});
onloadstart = (event) => {};
事件型別
js
事件屬性
一個 ProgressEvent。繼承自 Event。
示例
一個 64 位無符號整數,表示基礎程序正在執行的工作量的總數。在使用 HTTP 下載資源時,這是 Content-Length(訊息主體的大小),不包括標頭和其他開銷。
HTML
即時示例
<div class="controls">
<input
class="xhr success"
type="button"
name="xhr"
value="Click to start XHR (success)" />
<input
class="xhr error"
type="button"
name="xhr"
value="Click to start XHR (error)" />
<input
class="xhr abort"
type="button"
name="xhr"
value="Click to start XHR (abort)" />
</div>
<textarea readonly class="event-log"></textarea>
JavaScript
在諸如
addEventListener() 之類的 方法中使用事件名稱,或設定事件處理程式屬性。const xhrButtonSuccess = document.querySelector(".xhr.success");
const xhrButtonError = document.querySelector(".xhr.error");
const xhrButtonAbort = document.querySelector(".xhr.abort");
const log = document.querySelector(".event-log");
function handleEvent(e) {
log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`;
}
function addListeners(xhr) {
xhr.addEventListener("loadstart", handleEvent);
xhr.addEventListener("load", handleEvent);
xhr.addEventListener("loadend", handleEvent);
xhr.addEventListener("progress", handleEvent);
xhr.addEventListener("error", handleEvent);
xhr.addEventListener("abort", handleEvent);
}
function runXHR(url) {
log.textContent = "";
const xhr = new XMLHttpRequest();
addListeners(xhr);
xhr.open("GET", url);
xhr.send();
return xhr;
}
xhrButtonSuccess.addEventListener("click", () => {
runXHR("example-image.jpg");
});
xhrButtonError.addEventListener("click", () => {
runXHR("https://example.com/notfound.jpg");
});
xhrButtonAbort.addEventListener("click", () => {
runXHR("example-image.jpg").abort();
});
html
規範
| 結果 |
|---|
| 規範 # XMLHttpRequest 標準 |
| 規範 # event-xhr-loadstart |
瀏覽器相容性
handler-xhr-onloadstart