XMLHttpRequest: loadend イベント

loadend イベントは、リクエストが完了したときに、成功した場合(load の後)、成功しなかった場合(abort または error の後)のどちらでも発行されます。

構文

このイベント名を addEventListener() などのメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。

js
addEventListener("loadend", (event) => {});

onloadend = (event) => {};

イベント型

ProgressEvent です。 Event から継承しています。

Event ProgressEvent

イベントプロパティ

下記のプロパティに加え、親インターフェイスである Event のプロパティを利用できます。

lengthComputable 読取専用

論理値で、このプロセスで行われる作業の合計と、すでに行われた作業の量が計算可能かどうかを示す。言い換えれば、進捗が計測可能かどうかを示します。

loaded 読取専用

64 ビット符号なし整数値で、このプロセスで既に作業を行った量を示します。作業した比率は、total をこのプロパティの値で割ることで算出できます。 HTTP を使用してリソースをダウンロードする場合、これは HTTP メッセージの本文のみをカウントし、ヘッダーやその他のオーバーヘッドは含まれません。

total 読取専用

64 ビット符号なし整数で、基礎となるプロセスが実行中の作業の総量を表します。 HTTP を使用してリソースをダウンロードする場合、これは Content-Length (メッセージの本文のサイズ)であり、ヘッダーやその他のオーバーヘッドは含まれません。

ライブデモ

HTML

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

js
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(
    "https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json",
  );
});

xhrButtonError.addEventListener("click", () => {
  runXHR("http://i-dont-exist");
});

xhrButtonAbort.addEventListener("click", () => {
  runXHR(
    "https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json",
  ).abort();
});

結果

仕様書

Specification
XMLHttpRequest Standard
# event-xhr-loadend
XMLHttpRequest Standard
# handler-xhr-onloadend

ブラウザーの互換性

BCD tables only load in the browser

関連情報