页面加载
根据网页的复杂程度,浏览器可能需要一些事件才能完全加载网页。您可以在 window 对象(表示浏览器窗口)产生的 load (加载)事件上添加一个事件监听器,以了解何时发生这种情况。这避免了 JavaScript 与未完全加载的页面进行交互的混乱情况。
页面完全加载后,以下代码会在控制台中显示一条消息。
// Web page loading event
window.addEventListener("load", e => {
console.log("The page has been loaded!");
});
页面关闭
您有时想对页面关闭做出响应。当用户关闭显示网页的选项卡或导航到此选项卡中的另一个页面时,就是发生关闭。一个常见的例子是向用户显示一个确认对话框。处理页面关闭是通过在窗口对象上添加 beforeunload 事件处理程序来完成的。
// Handle page closing
window.addEventListener("beforeunload", e => {
const message = "Should you stay or should you go?";
// Standard way of showing a confirmation dialog
e.returnValue = message;
// Browser-specific way of showing a confirmation dialog
return message;
});
在 Event 对象上设置 returnValue 属性的值是触发显示此值的确认对话框的标准方式。但是,有些浏览器使用事件监听器的返回值代替。前面的代码将这两种技术联系起来以实现通用。