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).
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).
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 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).
The document.readyState property represents the current state of the document and has three possible values, corresponding to different document loading stages:
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 }
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
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:
Scripts that do not block the DOMContentLoaded event include:
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>
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.
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).
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.
Wait, HTML Has a Lifecycle? is the Next-Gen Serverless Platform for Web Hosting, Async Tasks, and Redis:
Multi-Language Support
Deploy unlimited projects for free
Unbeatable Cost Efficiency
Streamlined Developer Experience
Effortless Scalability and High Performance
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!