load

当整个页面及所有依赖资源如样式表和图片都已完成加载时,将触发load事件。

它与DOMContentLoaded不同,后者只要页面DOM加载完成就触发,无需等待依赖资源的加载。

是否冒泡
能否取消
接口 Event
Event handler property onload

用法

当页面及资源完全加载后在控制台打印一段信息:

window.addEventListener('load', (event) => {
  console.log('page is fully loaded');
});

也可以使用onload实现:

window.onload = (event) => {
  console.log('page is fully loaded');
};

示例

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`;
});

结果

规范

Specification Status Comment
UI Events
load
Working Draft
HTML Living Standard
load event
Living Standard 此链接指向加载文档结束时执行步骤中的部分。“load”事件也会在许多元素上触发。 请注意,规范中有很多地方涉及到可以"延迟加载事件"的内容。

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
load eventChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 4Opera Full support 4Safari Full support 1.3WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0

Legend

Full support  
Full support

参阅