XMLHttpRequest: loadstart イベント

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

loadstart イベントは、リクエストがデータを読み込み始めたときに発行されます。

構文

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

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

onloadstart = (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("example-image.jpg");
});

xhrButtonError.addEventListener("click", () => {
  runXHR("https://example.com/notfound.jpg");
});

xhrButtonAbort.addEventListener("click", () => {
  runXHR("example-image.jpg").abort();
});

結果

仕様書

Specification
XMLHttpRequest Standard
# event-xhr-loadstart
XMLHttpRequest Standard
# handler-xhr-onloadstart

ブラウザーの互換性

BCD tables only load in the browser

関連情報