--- title: 'Document: readystatechange 事件' slug: Web/Events/readystatechange事件 tags: - Reference - XMLHttpRequest - interactive - 事件 translation_of: Web/API/Document/readystatechange_event ---
{{APIRef}}

当文档的 {{domxref("Document.readyState", "readyState")}} 属性发生改变时,会触发 readystatechange 事件。

是否冒泡
是否可取消
接口 {{domxref("Event")}}
Event handler 属性 onreadystatechange

示例

实时演示

HTML

<div class="controls">
  <button id="reload" type="button">Reload</button>
</div>

<div class="event-log">
  <label>Event log:</label>
  <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea>
</div>

JS

const log = document.querySelector('.event-log-contents');
const reload = document.querySelector('#reload');

reload.addEventListener('click', () => {
  log.textContent ='';
  window.setTimeout(() => {
      window.location.reload(true);
  }, 200);
});

window.addEventListener('load', (event) => {
    log.textContent = log.textContent + 'load\n';
});

document.addEventListener('readystatechange', (event) => {
    log.textContent = log.textContent + `readystate: ${document.readyState}\n`;
});

document.addEventListener('DOMContentLoaded', (event) => {
    log.textContent = log.textContent + `DOMContentLoaded\n`;
});

结果

规范

规范 状态 备注
{{SpecName("HTML WHATWG", "indices.html#event-readystatechange", "readystatechange")}} {{Spec2("HTML WHATWG")}}

浏览器兼容性

{{Compat("api.Document.readystatechange_event")}}

IE 浏览器是一直支持 readystatechange 事件的,可作为 DOMContentLoaded 事件的替代方法(参见Browser compatibility的注释 [2])。

参见