HTML Native Lifecycle (Lifecycle) typically refers to the events and stages that a browser experiences when loading and processing a webpage. Although HTML itself is a markup language and lacks lifecycle hooks like JavaScript, HTML lifecycle events are actually managed through JavaScript interactions with the DOM (Document Object Model).
HTML Parsing
When the browser loads a webpage, it receives an HTML file from the server and begins parsing it. During this stage, the browser creates a DOM tree (Document Object Model) and converts the HTML into manipulable DOM objects.
Strictly speaking, HTML parsing is an essential phase in the page load process but does not fall into the category of "lifecycle events" in the traditional sense, as it cannot be captured or listened to directly via JavaScript. However, from a broader perspective, HTML parsing is an indispensable part of the overall page lifecycle, making it a critical component in discussions about the HTML lifecycle.
This process is internal to the browser, so developers cannot directly listen to this phase. However, they can improve parsing speed by optimizing the HTML structure and minimizing blocking resources (such as JavaScript files).
Loading External Resources
As the browser parses HTML, it encounters external resources. Depending on the resource type, loading method (synchronous or asynchronous), and priority, the browser decides how to continue loading and rendering the page. This behavior directly affects the rendering sequence of the page and the load time of content visible to users.
Different resource types have distinct loading behaviors, which influence page parsing and rendering:
CSS Loading: When the browser encounters a
<link>
tag, it pauses page rendering until the CSS file is fully loaded and parsed. CSS is considered a render-blocking resource because page layout and styles cannot render correctly without the CSS file.JavaScript Loading: By default, when the browser encounters a
<script>
tag, it halts HTML parsing until the JavaScript file is loaded and executed. This is known as synchronous loading. Synchronously loaded JavaScript blocks HTML parsing, affecting the timing of theDOMContentLoaded
andload
events.
Overall, loading external resources is closely tied to the page lifecycle because external resource loading impacts parsing, rendering, and the triggering of critical lifecycle events such as DOMContentLoaded
and load
. The shorter the external resource load time, the quicker lifecycle events are triggered.
readyState & readystatechange
readyState
and readystatechange
are two key browser attributes and events used to track the state of documents and network requests (such as AJAX requests). They help developers understand different stages of the webpage loading process and execute corresponding operations during these stages. They are primarily used in the context of document loading and network requests (e.g., XMLHttpRequest
).
document.readyState
The document.readyState
property represents the current state of the document and has three possible values, corresponding to different document loading stages:
-
loading
: The document is still loading, and the HTML is still being parsed. The DOM tree has not been fully constructed yet. External resources (like images and stylesheets) might not have been loaded or processed. -
interactive
: The document's HTML has been completely loaded and parsed, and the DOM tree has been built. However, stylesheets, images, and other resources might not be fully loaded yet. -
complete
: All resources on the page, including HTML, CSS, JavaScript, images, and subframes, have been fully loaded and processed. The page is completely ready.
Using document.readyState
, developers can check the document's loading state and perform corresponding actions based on different states. For example:
if (document.readyState === 'complete') {
// The page is fully loaded; perform page operations
}
readystatechange
Event
The readystatechange
event is triggered when the document's readyState
changes. Developers can listen to the readystatechange
event to execute specific logic at different loading stages. For instance:
document.addEventListener('readystatechange', function () {
if (document.readyState === 'interactive') {
// The DOM tree has been completely built; DOM manipulation is now possible
console.log('DOM is fully parsed');
} else if (document.readyState === 'complete') {
// The entire page, including all resources, is fully loaded
console.log('Page and resources are fully loaded');
}
});
Below is an HTML example illustrating the use of document.readyState
and readystatechange
to track different document loading stages. The page contains basic HTML elements and displays corresponding content or information at different readyState
stages:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document ReadyState Example</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.status {
font-size: 1.2em;
color: #333;
margin: 20px 0;
}
img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<script>
function updateStatus() {
console.log(document.readyState);
switch (document.readyState) {
case 'loading':
console.log('loading');
break;
case 'interactive':
console.log('interactive');
break;
case 'complete':
console.log('complete');
break;
}
}
updateStatus();
document.addEventListener('readystatechange', updateStatus);
</script>
</body>
</html>
The output of the above code:
loading
interactive
complete
DOMContentLoaded Event
The DOMContentLoaded
event is a key event triggered by the browser during the HTML document's loading process. It signifies that all elements in the HTML document have been completely parsed and the DOM tree has been constructed. However, external resources like images, stylesheets, and videos might not have finished loading. This is the primary distinction between DOMContentLoaded
and the load
event.
The DOMContentLoaded
event occurs on the document
object and must be captured using addEventListener
:
document.addEventListener('DOMContentLoaded', () => {});
The DOMContentLoaded
event is triggered when the browser finishes parsing the HTML document and generates all the DOM nodes. However, it does not require external resources (e.g., images, videos, stylesheets, or font files) to be fully loaded.
For example, if the page contains a large image, the DOMContentLoaded
event will fire before the image is fully loaded. At this point, the DOM tree is fully constructed, and developers can manipulate and access the DOM elements on the page. Here is an example:
<script type="text/javascript">
function ready() {
console.log('DOM is ready.');
const img = document.querySelector('#img');
// At this point, the image might not be fully loaded (unless it is cached),
// so its size will be 0x0.
console.log(`Image size: ${img.offsetWidth}x${img.offsetHeight}`);
}
document.addEventListener('DOMContentLoaded', ready);
</script>
<img
id="img"
src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
/>
The output of this code will appear as follows, with the DOM fully parsed before the image loads:
DOM is ready.
Image size: 0x0
If there are synchronous JavaScript files on the page (i.e., scripts without the async
or defer
attributes), the browser will pause HTML parsing when encountering a <script>
tag, wait for the script to execute, and then continue parsing. This will delay the triggering of the DOMContentLoaded
event.
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', () => {
console.log('DOM ready!');
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js"></script>
<script type="text/javascript">
console.log('Library loaded, inline script executed');
</script>
Output order:
Library loaded...
DOM ready!
Scripts that do not block the DOMContentLoaded
event include:
- Scripts with the
async
attribute - Scripts dynamically added to the webpage using
document.createElement('script')
window.onload Event
The load
event is triggered on the window
object when the entire page, including styles, images, and other resources, is fully loaded. This event can be captured using the onload
property.
Here is an example where the image's size is correctly displayed because window.onload
waits until all images are fully loaded:
<script type="text/javascript">
window.onload = function () {
console.log('Page loaded');
// At this point, the image is fully loaded
console.log(`Image size: ${img.offsetWidth}x${img.offsetHeight}`);
};
</script>
<img
id="img"
src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
/>
The output of this code will differ from the earlier example because onload
waits for all resources to finish loading:
Page loaded
Image size: 544x184
window.onbeforeunload Event
The beforeunload
event is triggered just before the page is about to be unloaded (e.g., when the user navigates to another page, closes the tab, or refreshes the page). This event allows developers to prompt the user to confirm if they really want to leave the page. It is typically used to remind users to save unsaved data or alert them about potential data loss.
Browsers allow a short message to be displayed during this event, asking users if they are sure they want to leave the page. For example, when users have entered content into an unsaved form, developers can use beforeunload
to prevent accidental page closure or refresh.
Modern browsers do not display custom prompt messages. Instead, they show a standardized warning message. Here’s an example:
window.onbeforeunload = function () {
return false;
};
When users attempt to leave the page, this event triggers a confirmation dialog, asking them whether they want to leave or stay on the page.
Due to security and user experience concerns, browsers ignore most custom messages and instead display a generic dialog. Overusing beforeunload
may degrade user experience, so it should only be used when absolutely necessary, such as in cases of unsaved data.
unload Event
The unload
event is triggered when the page is completely unloaded (e.g., when the page is closed, refreshed, or navigated away from). Unlike beforeunload
, the unload
event cannot prevent users from leaving the page. It is mainly used for performing final cleanup tasks, such as clearing temporary data, canceling asynchronous requests, and releasing memory.
The unload
event cannot prompt users, unlike beforeunload
. Instead, it is used for operations like closing WebSocket connections, saving data to local storage, or clearing timers.
One specific application of the unload
event is to send analytics data before the page unloads. The navigator.sendBeacon(url, data)
method can be used to send data in the background without delaying page unloading. For example:
const analyticsData = {
// Object containing collected data
};
window.addEventListener('unload', function () {
navigator.sendBeacon('/analytics', JSON.stringify(analyticsData));
});
When the sendBeacon
request is complete, the browser may have already left the document, so no server response is retrievable (the response is often empty for analytics purposes).
Summary
HTML parsing forms the foundation of the page lifecycle, but it is not itself a JavaScript-listenable lifecycle event. The DOMContentLoaded
event is triggered when the DOM tree is fully constructed, while the load
event fires after all resources on the page are completely loaded. The beforeunload
event prompts users to confirm navigation away from the page, and the unload
event is used for resource cleanup during page unloading. These events provide developers with control over the page loading and unloading processes, helping improve user experience and page performance.
We are Leapcell, your top choice for hosting Node.js projects.
Leapcell is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
- Develop with Node.js, Python, Go, or Rust.
Deploy unlimited projects for free
- pay only for usage — no requests, no charges.
Unbeatable Cost Efficiency
- Pay-as-you-go with no idle charges.
- Example: $25 supports 6.94M requests at a 60ms average response time.
Streamlined Developer Experience
- Intuitive UI for effortless setup.
- Fully automated CI/CD pipelines and GitOps integration.
- Real-time metrics and logging for actionable insights.
Effortless Scalability and High Performance
- Auto-scaling to handle high concurrency with ease.
- Zero operational overhead — just focus on building.
Explore more in the Documentation!
Follow us on X: @LeapcellHQ
Top comments (0)