Table of Contents
Hello World
Home Web Front-end JS Tutorial Wait, HTML Has a Lifecycle?

Wait, HTML Has a Lifecycle?

Jan 24, 2025 am 08:32 AM

Wait, HTML Has a Lifecycle?

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:

  1. 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.

  2. 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:

  1. 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.
  2. 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.
  3. 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
}
Copy after login
Copy after login
Copy after login

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');
  }
});
Copy after login
Copy after login

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 id="Hello-World">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>
  

Copy after login
Copy after login

The output of the above code:

loading
interactive
complete
Copy after login
Copy after login

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', () => {});
Copy after login

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
}
Copy after login
Copy after login
Copy after login

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');
  }
});
Copy after login
Copy after login

Output order:

  1. Library loaded...
  2. 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 id="Hello-World">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>
  

Copy after login
Copy after login

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
Copy after login
Copy after login

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
}
Copy after login
Copy after login
Copy after login

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?

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!

Try Wait, HTML Has a Lifecycle?

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles