How do JavaScript Page Lifecycle Events work
The lifecycle of an HTML page has three important events:
DOMContentLoaded
– the browser fully loaded HTML, and the DOM tree is built, but external resources like picturesimg
and stylesheets may be not yet loaded.load
– the browser loaded all resources (images, styles etc).beforeunload/unload
– when the user is leaving the page.
Each event may be useful:
DOMContentLoaded
event – DOM is ready, so the handler can lookup DOM nodes, initialize the interface.load
event – additional resources are loaded, we can get image sizes (if not specified in HTML/CSS) etc.beforeunload/unload
event – the user is leaving: we can check if the user saved the changes and ask him whether he really wants to leave.
Let’s explore the details of these events.
document.addEventListener("DOMContentLoaded", (e) => { alert("your dome is ready"); }) window.addEventListener("load", (e) => { alert("your image is ready"); }) window.addEventListener("beforeunload", (e) => { return e.returnValue = "Something random.."; })