Web Application Lifecycle Overview
Client-side web applications begin their lifecycle when users enter a URL or click a link. The browser sends a request to the server, which processes it and returns a response typically composed of HTML, CSS, and JavaScript. Upon receiving this response, the application undergoes two primary phases:
- Page Construction – Building the user interface
- Event Handling – Entering an event loop to process user interactions
The application lifecycle concludes when the user navigates away or closes the page.
Page Construction Phase
The page construction phase involves parsing HTML to build the Document Object Model (DOM) and executing JavaScript code. This process occurs in alternating steps until all HTML elements are processed.
HTML Parsing and DOM Construction
Browser begins constructing the UI by parsing HTML and building DOM nodes. Each HTML element becomes a node in a tree structure where every node (except the root) has exactly one parent and may have multiple children.
When the parser encounters a <script> element, it pauses DOM construction to execute JavaScript code.
JavaScript Execution
The global window object serves as the main interface to the browser environment. Its document property provides access to the DOM, enabling JavaScript to modify page structure dynamically.
JavaScript code exists in two forms:
- Global code – Executed immediately when encountered
- Function code – Executed only when called
Event Handling Phase
JavaScript uses a single-threaded execution model where only one piece of code can run at a time. The event handling process followss this pattern:
- Browser checks the event queue
- If events exist, processes them in order
- Executes associated event handlers
- Returns to checking the queue
Events occur asynchronously and can include:
- Browser events (page load, errors)
- Network events (AJAX responses)
- User events (clicks, keyboard input)
- Timer events (setTimeout, setInterval)
Registering Event Handlers
Event handlers are functions that execute when specific events occur. Two primary registration methods exist:
// Method 1: Assign to properties (not recommended)
window.onload = function() { /* initialization */ };
// Method 2: Use addEventListener (preferred)
document.body.addEventListener('click', function() {
console.log('Body clicked');
});
The addEventListener method allows multiple handlers for the same event type, unlike property assignment which overwrites previous handlers.
Event Processing
When events occur, browsers place them in a queue. The event loop processes events sequentially, invoking their associated handlers. Only after a handler completes execution does the next event get processed.
This ensures predictable handling order but means long-running handlers can make applications unresponsive.