The document object represents the web page loaded in the browser and serves as the entry point into the DOM tree. It provides global document properties, document state indicators, and lifecycle event hooks.
flowchart TD
Navigation["User Navigates to URL"] --> Parsing["HTML Parsing Begins"]
Parsing --> DOMReady["DOMContentLoaded Event (DOM Tree Fully Parsed)"]
DOMReady --> ResourceLoad["Images, CSS, & Frames Finish Loading"]
ResourceLoad --> WindowLoad["window.onload Event (Page Fully Loaded)"]
WindowLoad --> UserExit["User Navigates Away"]
UserExit --> Unload["visibilitychange / beforeunload Events"]
document Properties| Property | Description | Example Output |
|---|---|---|
document.title |
Reads or sets HTML <title> tag. |
"KodSolution Tutorials" |
document.body |
References <body> element node. |
<body class="dark-mode"> |
document.head |
References <head> element node. |
<head> |
document.URL |
Returns full current document URL string. | "https://kodersolution.com/js" |
document.referrer |
Returns URL of page that linked to current page. | "https://google.com" |
document.readyState |
Document loading state ("loading", "interactive", "complete"). |
"complete" |
// Demonstrating document properties and lifecycle listeners
// 1. Modifying Document Metadata
document.title = "JavaScript DOM Document | KodSolution";
console.log(`Current Document URL: ${document.URL}`);
console.log(`Referrer Page: ${document.referrer || "Direct Visit"}`);
// 2. DOMContentLoaded Lifecycle Hook (DOM Parsed)
document.addEventListener("DOMContentLoaded", () => {
console.log(`DOMContentLoaded Fired! ReadyState: ${document.readyState}`);
});
// 3. Window Load Lifecycle Hook (Full Resources Loaded)
window.addEventListener("load", () => {
console.log("Window Load Fired! All images and stylesheets loaded.");
});
// 4. Page Visibility API
document.addEventListener("visibilitychange", () => {
if (document.hidden) {
console.log("User switched tabs (Page Hidden). Pausing video/timers.");
} else {
console.log("User returned to tab (Page Visible). Resuming active features.");
}
});
DOMContentLoaded for Script Initialization: Initialize application components on DOMContentLoaded rather than waiting for window.onload.visibilitychange Instead of beforeunload: Modern mobile browsers do not reliably fire unload or beforeunload. Use document.addEventListener("visibilitychange") to save user state.document.readyState Checks: If running inside an async script module, check if (document.readyState !== "loading") before adding DOMContentLoaded listeners.What is the difference between the DOMContentLoaded event and the window.load event?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.