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 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 the DOMContentLoaded and load events.</script>
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:
<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> <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>
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:
if (document.readyState === 'complete') { // The page is fully loaded; perform page operations }
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.<br> </script>
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'); } });
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:
<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> <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>
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:
loading interactive complete
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:
if (document.readyState === 'complete') { // The page is fully loaded; perform page operations }
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 Wait, HTML Has a Lifecycle?, your top choice for hosting Node.js projects.
Wait, HTML Has a Lifecycle? 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: @Wait, HTML Has a Lifecycle?HQ
Read on our blog
The above is the detailed content of Wait, HTML Has a Lifecycle?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
