search
HomeWeb Front-endJS TutorialWait, HTML Has a Lifecycle?

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
}

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

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:

  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>
  

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?

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
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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.