PadhaikoAll subjects

Introduction

Web Application Programming (ENCT 302)

Open in the Padhaiko app

1.1 Overview of web applications and evolution of web architecture

A web application is a client-server software application that executes business logic, manages dynamic state, and persists data across networks, accessed by users through a standard web browser. Unlike a traditional static website that serves pre-composed HTML, CSS, and image files directly from a filesystem, a web application processes user input, interacts with relational or non-relational databases, executes backend logic, and dynamically synthesizes responses.

Definition

Web Application vs. Static Website

A static website delivers identical, pre-rendered content (HTML/CSS/assets) to all users directly from storage media or Content Delivery Networks (CDNs), without server-side processing or dynamic database queries. A web application is an interactive software program executed across browser and server runtimes, featuring bidirectional user communication, session handling, state management, role-based authentication, and transaction processing.

Evolution of Web Architecture

Web architecture has progressed through four distinct architectural generations to satisfy expanding enterprise demands for responsiveness, scalability, maintainability, and user experience:

  1. First Generation: Static and CGI Web (Web 1.0, Early 1990s): Early web architectures relied on simple file servers delivering static HyperText Markup Language (HTML) documents via the HyperText Transfer Protocol (HTTP). When dynamic behavior was required, web servers invoked external executable scripts using the Common Gateway Interface (CGI). Each incoming HTTP request spawned a new operating system process (Perl, C, or Shell script), executed the query, streamed generated HTML back to the browser, and terminated. This model suffered severe performance bottlenecks due to excessive operating system process-creation overhead and zero memory sharing between requests.
  2. Second Generation: Server-Side Rendered Dynamic Web (Web 2.0, Late 1990s to 2000s): The introduction of in-process application servers and embedded scripting engines (such as PHP, Active Server Pages (ASP), JavaServer Pages (JSP), and Apache modules like mod_php) eliminated per-request process creation. Requests were handled by persistent worker threads. The architecture standardized around the classic LAMP stack (Linux, Apache, MySQL, PHP/Python/Perl). Every user interaction (such as submitting a form or clicking pagination) triggered a full-page reload cycle: the server executed database queries, composed an entirely new HTML document on the fly, and transmitted the full payload across the network.
  3. Third Generation: Single Page Applications (SPAs) and RESTful Web Services (2010s): Driven by browser runtime enhancements (high-performance JavaScript V8 engines, ECMAScript standards, and the W3C XMLHttpRequest / Fetch API), web applications separated presentation from backend logic. The server transitioned into a headless provider of RESTful APIs transmitting raw JSON or XML data. The browser downloaded an initial minimal HTML shell and a bundled JavaScript payload (using frameworks such as React, Angular, or Vue). Client-side routers intercepted URL navigation, fetched structured data asynchronously in the background via AJAX/Fetch, and dynamically updated specific Document Object Model (DOM) subtrees without reloading the page.
  4. Fourth Generation: JAMstack, Micro-Frontends, and Serverless Edge Architectures (2020s to Present): Modern web systems combine the performance advantages of pre-rendered static content with dynamic runtime flexibility. The JAMstack (JavaScript, APIs, Pre-rendered Markup) pre-compiles pages at build time using Static Site Generation (SSG) and hydrates them with client-side JavaScript. Hybrid frameworks (such as Next.js, Remix, and Nuxt) blend Server-Side Rendering (SSR), Incremental Static Regeneration (ISR), and Client-Side Rendering (CSR). Concurrently, cloud architectures have evolved toward Serverless functions (AWS Lambda, Cloudflare Workers) deployed to edge CDN nodes worldwide, reducing latency by executing business logic in close physical proximity to the user.
Architectural Comparison of Web Evolution Stages
Architectural AttributeWeb 1.0 (Static & CGI)Web 2.0 (Server-Side Rendered)Web 3.0 / SPAs (Client-Side Rendered)Modern Hybrid / JAMstack
Primary Execution LocationWeb server file-system / CGIServer-side template engineClient browser JavaScript engineDistributed Edge + Browser hydration
Data Exchange FormatRaw HTML documentsFully rendered HTML pagesJSON / Protocol Buffers via REST/GraphQLPre-rendered HTML + JSON payloads
Page Navigation ExperienceFull-page reloadFull-page reloadSeamless client-side route transitionsInstant pre-fetched page transitions
State ManagementStateless, file-basedServer-side sessions (Cookies/Session ID)Client-side stores (Redux, Context) + JWTHybrid (Edge KV, JWT, Local cache)
Initial Page Load LatencyVery fast (static files)Moderate (server processing latency)Slow (large JavaScript bundles to parse)Extremely fast (cached static edge HTML)
Subsequent Route LatencySlow (fresh document fetch)Slow (full document re-fetch)Extremely fast (only raw JSON fetched)Instant (pre-cached chunks and assets)

Multi-Tier Web Application Architecture

Enterprise web applications are structured into distinct logical tiers to maintain separation of concerns, improve horizontal scalability, and isolate security boundaries:

Classic Three-Tier Web Application ArchitectureText
  [ User Agent / Client Tier ]
    - Web Browser (HTML5, CSS3, JavaScript, SPA Frameworks, Mobile Web)
    - Responsibilities: Rendering UI, capturing user events, input pre-validation
                 |
                 | HTTP / HTTPS (JSON, Form-Data, WebSockets)
                 v
  [ Application / Logic Tier ]
    - Web Server (Nginx, Apache) -> Reverse Proxy, SSL Termination, Static Cache
    - Application Server (Django, Node.js, Spring Boot, ASP.NET)
    - Responsibilities: Authentication, Authorization, Routing, Business Rules, ORM
                 |
                 | Database Protocols (TCP/IP, Connection Pooling)
                 v
  [ Data / Persistence Tier ]
    - Relational Databases (PostgreSQL, MySQL) & NoSQL Stores (MongoDB, Redis)
    - Responsibilities: ACID transactions, persistent indexing, query optimization
  1. Presentation Tier (Client Layer): The interface executed inside the client browser. It translates application state into visual representations using HTML and CSS, collects user inputs, performs immediate client-side validation, and dispatches asynchronous requests to the application tier.
  2. Application Tier (Business Logic Layer): Hosted on centralized or distributed servers. It authenticates identity, authorizes permissions, enforces domain-specific business rules, processes algorithmic workloads, coordinates transactions, and maps data between persistence schemas and client representations.
  3. Data Tier (Storage Layer): Manages enterprise persistent state. It guarantees data durability, enforces referential integrity constraints, executes indexed queries, and manages cache coherency across disk and in-memory caches.

1.2 Client-server architecture, HTTP, HTTPS, URLs, DNS, web browsers

Web applications rely on distributed networking foundations governed by standardized protocols across the Internet protocol suite.

Client-Server Architecture

The client-server model is a distributed computing structure that partitions tasks between service providers (servers) and service requesters (clients).

Uniform Resource Locators (URLs) and URIs

A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource. A Uniform Resource Locator (URL) is a specific subset of URI that specifies the primary access mechanism (network location and protocol) for retrieving the resource.

Anatomy of a Uniform Resource Locator (URL)Text
  https://engineering.tu.edu.np:443/academics/courses?sem=5&type=regular#syllabus
  \___/   \____________________/ \___/ \________________/ \____________/ \______/
    |               |              |           |                 |           |
  Scheme         Hostname        Port        Path           Query String  Fragment
  1. Scheme (Protocol): Declares the protocol used to access the resource (e.g., http, https, ftp, ws). It determines the default transport port, security handshake, and syntax rules.
  2. Hostname (Domain or IP Address): Identifies the host server providing the service. It can be a fully qualified domain name (FQDN) resolved by DNS, or a literal IPv4 (192.168.1.1) or IPv6 address ([2001:db8::1]).
  3. Port: An integer between 1 and 65535 indicating the transport-layer TCP port. If omitted, standard defaults apply: port 80 for HTTP and port 443 for HTTPS.
  4. Path: Hierarchical string identifying the specific file, resource endpoint, or route handler within the server namespace (e.g., /academics/courses).
  5. Query String: Begins with a question mark (?) containing key-value pairs delimited by ampersands (&), such as sem=5&type=regular. It passes non-hierarchical parameters to the server endpoint.
  6. Fragment Identifier: Begins with a hash symbol (#). It is processed exclusively by the client browser to scroll to an internal anchor or maintain client-side routing state; it is never transmitted to the web server in the HTTP request line.

Domain Name System (DNS)

The Domain Name System (DNS) is a hierarchical, decentralized naming system that translates human-friendly domain names (e.g., tu.edu.np) into numerical Internet Protocol (IP) addresses required for routing network packets (e.g., 103.10.235.4).

Hierarchical DNS Resolution FlowText
  [ Web Browser ]
        | 1. Query: "tu.edu.np"
        v
  [ Recursive DNS Resolver (ISP / 8.8.8.8) ]
        | 2. Ask Root Server (".")
        v
  [ Root DNS Nameserver ] ----> 3. Refers to ".np" ccTLD Server
        |
        | 4. Ask TLD Server
        v
  [ TLD Nameserver (".np") ] -> 5. Refers to Authoritative Server for "tu.edu.np"
        |
        | 6. Ask Authoritative Server
        v
  [ Authoritative DNS Server ] -> 7. Returns A Record: 103.10.235.4
        |
        +-----------------------> 8. Returns IP to Browser (and caches result)

Key DNS Resource Record types utilized in web deployment:

HyperText Transfer Protocol (HTTP)

HTTP is an application-layer, stateless protocol operating over TCP/IP. It defines the structured syntax of messages exchanged between browsers and web servers.

HTTP Message Structure

Both requests and responses share a four-part textual architecture:

  1. Start Line: In requests, the Request Line contains the method, target path, and protocol version (e.g., GET /index.html HTTP/1.1). In responses, the Status Line contains the protocol version, numeric status code, and reason phrase (e.g., HTTP/1.1 200 OK).
  2. Headers: Key-value pairs providing metadata about client capabilities, payload encoding, cookies, caching directives, and security policies (e.g., Host: tu.edu.np, Content-Type: application/json).
  3. Empty Line: A mandatory Carriage Return and Line Feed (\r\n) separating headers from the body.
  4. Message Body (Payload): Optional binary or textual data (e.g., form submissions, JSON objects, HTML documents, or image data).

Standard HTTP Methods

HTTP defines standard verbs indicating the desired action to be performed on a target resource. These methods are categorized by two critical properties:

HTTP Request Methods Properties
HTTP MethodPrimary PurposeSafe?Idempotent?Typical Request Body?
GETRetrieve a representation of a specified resourceYesYesNo
HEADRetrieve only HTTP headers identical to GET, without bodyYesYesNo
POSTSubmit data to be processed; create a new subordinate resourceNoNoYes (Form / JSON)
PUTReplace the complete target resource with the uploaded payloadNoYesYes (Complete entity)
PATCHApply partial modifications to an existing resourceNoNoYes (Delta instructions)
DELETERemove the target resource from the serverNoYesRarely
OPTIONSDescribe communication options and CORS capabilitiesYesYesNo

HTTP Status Codes

The server indicates request execution outcomes through three-digit status codes grouped into five distinct classes:

Protocol Evolution: HTTP/1.1 vs. HTTP/2 vs. HTTP/3

HTTPS (HTTP Secure) and Transport Layer Security (TLS)

HTTPS tunnels standard HTTP message traffic through an encrypted cryptographic channel established by Transport Layer Security (TLS) (formerly SSL). It guarantees three fundamental security tenets:

  1. Confidentiality: Eavesdroppers cannot read intercepted plaintext traffic (protecting credentials, personal records, and session cookies).
  2. Integrity: Digital signatures and Message Authentication Codes (MACs) ensure data cannot be modified or corrupted in transit without immediate detection.
  3. Authentication: Server identity is cryptographically validated using X.509 Digital Certificates signed by trusted third-party Certificate Authorities (CAs), preventing Man-in-the-Middle (MitM) impersonation.

The TLS 1.3 handshake establishes mutual cryptographic session keys in a single round-trip (1-RTT) using ephemeral Diffie-Hellman key exchange, ensuring Perfect Forward Secrecy (PFS).

Web Browser Architecture and the Critical Rendering Path

A modern web browser is a multi-process operating environment composed of key architectural subsystems:

Definition

Critical Rendering Path (CRP)

The Critical Rendering Path is the sequential series of steps a web browser executes to convert raw HTML, CSS, and JavaScript bytes received from the network into rendered pixels on the visual display:

  1. DOM Construction: Parsing HTML bytes into characters, tokens, nodes, and assembling the Document Object Model (DOM) tree.
  2. CSSOM Construction: Parsing CSS rules into style nodes and building the CSS Object Model (CSSOM) tree (render-blocking).
  3. Render Tree Generation: Combining visible DOM nodes with computed CSSOM styles into the Render Tree (omits non-visual elements like <head> and display: none).
  4. Layout (Reflow): Calculating exact geometric dimensions, coordinates, and positions for every visible box on the viewport.
  5. Paint (Rasterization): Filling in actual pixels (colors, borders, text, shadows) into bitmap layers.
  6. Compositing: Layering drawn surfaces on the GPU according to z-index and stacking contexts to render the final frame.

1.3 Html basics: Syntax, tags, attributes, forms and inputs, tables, lists, multimedia, semantic HTML5 elements

HyperText Markup Language (HTML) is the standard declarative markup language defining the structural scaffolding and semantic meaning of documents rendered on the World Wide Web.

HTML5 Document Anatomy and Syntax Rules

An HTML document comprises a hierarchical tree of elements, demarcated by opening tags, optional attributes, content, and closing tags. Void elements (such as <img>, <input>, <br>, <meta>, <hr>) possess no closing tags or internal content.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tribhuvan University Portal</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <header>
    <h1>Department of Electronics and Computer Engineering</h1>
  </header>
  <main>
    <p>Welcome to the Web Application Programming academic portal.</p>
  </main>
</body>
</html>

Key Structural Declarations:

Semantic HTML5 Elements vs. Non-Semantic Containers

Semantic HTML5 elements convey explicit machine-readable meaning regarding their enclosed content to browsers, assistive technologies (screen readers), and search engine bots.

AspectSemantic ElementsGeneric Containers (div / span)
Meaning & ContextClearly describes purpose (<nav>, <article>, <aside>, <main>)Carries zero inherent semantic meaning
Accessibility (a11y)Automatically maps to WAI-ARIA landmark roles for screen reader navigationRequires manual role="..." and ARIA attributes
Search Engine OptimizationPrioritizes content weighting (e.g., <article> vs <footer>)Search indexers treat contents uniformly
Code MaintainabilityClean, self-documenting structural layoutLeads to unmaintainable deeply nested "div soup"
Default StylingStandard block/inline behavior with semantic defaultsBlock (<div>) or inline (<span>) with zero styling

Core Semantic Layout Landmarks:

Lists and Tables

HTML provides structured elements for tabular and sequential information:

  1. Lists:
    • Unordered List (<ul>): Bulleted list of items (<li>) where order is arbitrary.
    • Ordered List (<ol>): Numbered or alphabetical sequence of items (<li>), configurable with start and type attributes.
    • Description List (<dl>): Pairs of terms (<dt>) and descriptions (<dd>), ideal for glossaries, metadata, and key-value displays.
  2. Tables: Tables represent two-dimensional structured relational data, composed with semantic row groupings:
HTML
<table border="1">
  <caption>Institute of Engineering Sem V Examination Schedule</caption>
  <thead>
    <tr>
      <th scope="col">Subject Code</th>
      <th scope="col">Course Title</th>
      <th scope="col">Marks</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>ENCT 302</td>
      <td>Web Application Programming</td>
      <td>80</td>
    </tr>
    <tr>
      <td>ENCT 301</td>
      <td>Database Management Systems</td>
      <td>80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th scope="row" colspan="2">Total Core Weightage</th>
      <td>160</td>
    </tr>
  </tfoot>
</table>

scope="col" and scope="row" explicitly associate header cells with corresponding columns or rows, ensuring full screen-reader accessibility. colspan and rowspan merge adjacent cells horizontally or vertically.

Multimedia Elements: Images, Audio, and Video

Modern HTML delivers native media playback without external browser plugins:

Forms, Inputs, and HTML5 Validation

Forms constitute the primary user-input mechanism for transmitting data payloads to backend servers:

HTML
<form action="/api/v1/students/register" method="POST" enctype="application/x-www-form-urlencoded">
  <fieldset>
    <legend>Student Registration Form</legend>

    <div class="form-group">
      <label for="fullName">Full Name:</label>
      <input type="text" id="fullName" name="fullName" required minlength="3" maxlength="60" placeholder="e.g. Ramesh Thapa">
    </div>

    <div class="form-group">
      <label for="emailAddr">Campus Email:</label>
      <input type="email" id="emailAddr" name="email" required placeholder="[email protected]">
    </div>

    <div class="form-group">
      <label for="userPassword">Password:</label>
      <input type="password" id="userPassword" name="password" required minlength="8">
    </div>

    <div class="form-group">
      <label for="semesterSelect">Semester:</label>
      <select id="semesterSelect" name="semester">
        <option value="5" selected>Fifth Semester</option>
        <option value="6">Sixth Semester</option>
      </select>
    </div>

    <div class="form-group">
      <label for="remarks">Project Summary:</label>
      <textarea id="remarks" name="summary" rows="4" cols="50"></textarea>
    </div>

    <button type="submit">Complete Registration</button>
  </fieldset>
</form>

Critical Form Attributes:


1.4 CSS basics: Selectors, properties, values, box model

Cascading Style Sheets (CSS) is the declarative style language used to describe the visual presentation, formatting, and layout of documents structured in HTML.

Cascading, Specificity, and Inheritance

CSS operates under three foundational conflict-resolution principles when multiple rules target the same element:

  1. Importance and Origin: !important declarations override normal declarations. User-agent styles are superseded by user styles, which are superseded by author styles.
  2. Specificity: The weight assigned to a selector rule determining precedence. Specificity is calculated as a four-part vector (a, b, c, d):
    • a (Inline styles): Styles applied directly via style="..." attribute (Weight: 1000).
    • b (IDs): Number of ID selectors such as #header (Weight: 100).
    • c (Classes, attributes, pseudo-classes): .btn, [type="text"], :hover (Weight: 10).
    • d (Elements and pseudo-elements): h1, p, ::before, ::after (Weight: 1).
    • The universal selector (*), combinators (+, >, ~, space), and :where() carry zero specificity (0, 0, 0, 0).
  3. Source Order: When two rules possess identical specificity, the rule appearing latest in the stylesheet wins.
  4. Inheritance: Properties such as color, font-family, and line-height cascade automatically from parent containers to children, whereas layout properties like margin, padding, border, and display do not inherit.

CSS Selectors Reference

Selectors define the element matching criteria across the DOM tree:

The CSS Box Model

Every element rendered on an HTML page is represented as a rectangular layout structure consisting of four concentric layers:

Concentric Layers of the CSS Box ModelText
  +-------------------------------------------------------+
  | Margin (Transparent outer clearance between elements) |
  |   +-----------------------------------------------+   |
  |   | Border (Solid/dashed line enclosing element)  |   |
  |   |   +---------------------------------------+   |   |
  |   |   | Padding (Inner space around content)  |   |   |
  |   |   |   +-------------------------------+   |   |   |
  |   |   |   | Content Area (Text, Images)   |   |   |   |
  |   |   |   |   width x height              |   |   |   |
  |   |   |   +-------------------------------+   |   |   |
  |   |   +---------------------------------------+   |   |
  |   +-----------------------------------------------+   |
  +-------------------------------------------------------+
  1. Content Area: Contains the actual text, media, or child elements, governed by width and height.
  2. Padding: Transparent spacing surrounding the content inside the border. Clears background color/image.
  3. Border: Encloses content and padding; styles, widths, and colors are customizable.
  4. Margin: Transparent spacing outside the border, isolating the element from adjacent sibling elements. Vertical margins of adjacent block elements undergo margin collapsing.

Box-Sizing: content-box vs. border-box

The box-sizing CSS property determines whether padding and border dimensions expand the rendered box width or are contained within the declared width:

Aspectcontent-box (W3C Default)border-box (Modern Standard)
Declared Width Applies ToContent area onlyContent + Padding + Border combined
Rendered Outer Box Widthwidth + padding_left + padding_right + border_left + border_rightExact declared width
Internal Content WidthExact declared widthwidth - (padding_left + padding_right + border_left + border_right)
Layout PredictabilityComplex; adding padding unexpectedly expands elements, breaking grid percentagesIntuitive; elements consistently occupy declared percentage or pixel widths
Standard Best PracticeDeprecated for modern layoutsGlobally applied via * { box-sizing: border-box; }

Display Types and Modern Layouts

The display property controls an element's formatting context:


1.5 CSS framework: Bootstrap

A CSS framework is a pre-prepared software library containing standardized, tested CSS stylesheets and optional JavaScript components. It accelerates development by providing responsive grid systems, accessible UI components, typography scales, and atomic utility classes.

Advantages and Disadvantages of CSS Frameworks

Evaluation of CSS Frameworks (e.g., Bootstrap)
DimensionAdvantagesDisadvantages
Development SpeedPre-built navigation bars, cards, modals, and forms allow rapid prototypingOver-reliance creates generic "cookie-cutter" website aesthetics
Cross-Browser UniformityNormalizes CSS resets and vendor prefix discrepancies automaticallyUnused framework classes add bloat unless pruned with PurgeCSS
Mobile ResponsivenessBuilt-in mobile-first 12-column flexbox grid handles all viewport sizesDeeply nested framework classes clutter HTML markup
Accessibility (a11y)Components implement ARIA standards and keyboard focus traps out-of-the-boxOverriding opinionated framework styles requires high CSS specificity

The Bootstrap 12-Column Responsive Grid System

Bootstrap's layout engine uses a mobile-first 12-column flexbox grid, built upon three primary architectural containers:

  1. Container (.container or .container-fluid): Provides horizontal padding and centers content on screen. .container steps through fixed maximum widths at specific breakpoints, while .container-fluid spans 100% width across all viewports.
  2. Row (.row): Horizontal wrapper for columns that enforces negative margins to neutralize container padding and ensures column alignment.
  3. Columns (.col-*): Immediate children of rows. The integer suffix defines how many of the 12 available fractional columns an element occupies.

Bootstrap Breakpoint Tiers:

HTML
<div class="container my-4">
  <div class="row g-3">
    <!-- 12 cols on mobile, 6 cols on tablet, 4 cols on desktop -->
    <div class="col-12 col-md-6 col-lg-4">
      <div class="card p-3 shadow-sm">
        <h5 class="card-title">Engineering Math III</h5>
        <p class="card-text">Advanced differential equations and transforms.</p>
        <button class="btn btn-primary">Open Subject</button>
      </div>
    </div>
    <div class="col-12 col-md-6 col-lg-4">
      <div class="card p-3 shadow-sm">
        <h5 class="card-title">Web Application Programming</h5>
        <p class="card-text">Client and server web development architectures.</p>
        <button class="btn btn-success">Open Subject</button>
      </div>
    </div>
    <div class="col-12 col-md-12 col-lg-4">
      <div class="card p-3 shadow-sm">
        <h5 class="card-title">Database Systems</h5>
        <p class="card-text">Relational queries, ACID transactions, and normalization.</p>
        <button class="btn btn-warning">Open Subject</button>
      </div>
    </div>
  </div>
</div>

Atomic Utilities in Bootstrap 5

Bootstrap 5 features responsive utility classes for rapid layout styling without writing custom CSS:


Worked Examples

Example

CSS Box Model Dimensions Calculation

A web developer styles a card element with the following CSS declarations: width: 400px; height: 200px; padding: 25px; border: 5px solid #333; margin: 20px;

Calculate:

  1. The rendered outer box width and the total horizontal footprint occupied in the document layout under the default W3C box-sizing: content-box model.
  2. The rendered outer box width, the resulting inner content width, and the total horizontal footprint occupied under the modern box-sizing: border-box model.

Determine the box dimensions under content-box: Under box-sizing: content-box, the CSS width property configures only the central content area.

  • Content Width = 400 px
  • Horizontal Padding = padding-left + padding-right = 25 px + 25 px = 50 px
  • Horizontal Border = border-left + border-right = 5 px + 5 px = 10 px
  • Horizontal Margin = margin-left + margin-right = 20 px + 20 px = 40 px

The rendered outer box width (border-edge) is: Rendered Width = Content Width + Horizontal Padding + Horizontal Border Rendered Width = 400 + 50 + 10 = 460 px

The total horizontal layout space (including margins) is: Total Footprint = Rendered Width + Horizontal Margin = 460 + 40 = 500 px

Determine the box dimensions under border-box: Under box-sizing: border-box, the declared CSS width defines the total width up to the outer edge of the border.

  • Declared Width = Rendered Width = 400 px
  • Horizontal Padding = 25 px + 25 px = 50 px
  • Horizontal Border = 5 px + 5 px = 10 px
  • Horizontal Margin = 20 px + 20 px = 40 px

The inner content width available for text and images is compressed: Inner Content Width = Declared Width - (Horizontal Padding + Horizontal Border) Inner Content Width = 400 - (50 + 10) = 340 px

The total horizontal layout footprint occupied in the document is: Total Footprint = Declared Width + Horizontal Margin = 400 + 40 = 440 px

Answer:
  1. Under content-box: Rendered box width is 460 px; total horizontal layout footprint is 500 px.
  2. Under border-box: Rendered box width is 400 px; internal content width shrinks to 340 px; total horizontal layout footprint is 440 px.
Example

End-to-End Web Lifecycle: URL to Rendered Pixels

A student enters the following URL into a web browser: https://engineering.tu.edu.np:443/portal/login?ref=home#form

Trace the complete sequence of network protocols and browser operations executed from the moment the user presses Enter until the login screen is visually presented on the monitor.

URL Parsing and Local Cache Check: The browser parses the string into protocol (https), target hostname (engineering.tu.edu.np), port (443), path (/portal/login), query string (ref=home), and fragment (#form). The fragment #form is retained locally in browser memory and not sent to the server. The browser checks its internal HSTS list (confirming HTTPS), service worker cache, and DNS cache (browser DNS cache, OS cache, /etc/hosts).

DNS Resolution and Socket Establishment: Assuming a DNS cache miss, the OS queries the recursive DNS resolver. The resolver queries the Root DNS servers (.), the .np ccTLD nameserver, and finally the authoritative nameserver for tu.edu.np, which returns the A record IP address (e.g., 103.10.235.4). The browser opens a transport-layer socket by performing a TCP 3-way handshake (SYN -> SYN-ACK -> ACK) with 103.10.235.4 on port 443.

TLS Handshake and Secure Channel Negotiation: Over the established TCP stream, client and server execute the TLS 1.3 handshake:

  • Client sends ClientHello with supported cipher suites and key share parameters.
  • Server replies with ServerHello, presents its X.509 digital certificate signed by a trusted CA, and transmits its key share.
  • The browser validates certificate authenticity, expiration, and domain name against trusted root certificates stored in the OS/browser trust store.
  • Both endpoints derive symmetric encryption session keys. All subsequent data exchange is encrypted.

HTTP Request-Response Transmission: The browser constructs and transmits an HTTP/1.1 or HTTP/2 request:

Text
GET /portal/login?ref=home HTTP/1.1
Host: engineering.tu.edu.np
User-Agent: Mozilla/5.0
Accept: text/html,application/xhtml+xml

The server reverse proxy (Nginx) terminates TLS, routes the request to the application server (e.g., Django/Node.js), which queries the database, renders the HTML document, and returns: HTTP/1.1 200 OK along with Content-Type: text/html; charset=UTF-8 and the HTML byte stream in the body.

Critical Rendering Path Execution in Browser:

  1. The browser engine parses HTML bytes into tokens, generating the DOM tree.
  2. Encountering external <link rel="stylesheet">, the network subsystem fetches styles.css asynchronously and parses it into the CSSOM tree.
  3. DOM and CSSOM are merged into the Render Tree.
  4. The engine performs Layout, calculating exact pixel coordinates on the viewport.
  5. Painting rasterizes colors, borders, and text into bitmap layers.
  6. Compositing uploads GPU layers to screen.
  7. Finally, the browser scrolls the viewport down until the element with id="form" is aligned.
Answer:

The lifecycle executes: (1) URL parsing, (2) Hierarchical DNS resolution to target IP, (3) TCP three-way handshake on port 443, (4) TLS 1.3 cryptographic handshake validating X.509 certificate, (5) HTTP GET request and 200 OK HTML delivery, (6) Critical Rendering Path (DOM + CSSOM -> Render Tree -> Layout -> Paint -> Composite), and (7) viewport scrolling to the #form fragment anchor.

Example

CSS Specificity Calculation and Cascade Resolution

Evaluate the four CSS rules targeting the hyperlink element <a id="cta-link" class="nav-btn primary" href="/apply">Apply Now</a> nested inside <nav id="top-nav" class="navbar">:

Rule A: #top-nav .nav-btn a { color: blue; } Rule B: nav.navbar a.primary { color: green; } Rule C: #cta-link { color: red; } Rule D: <a ... style="color: purple;">

Calculate the specificity vector (Inline, ID, Class, Element) for Rules A, B, and C. Identify which rule wins the cascade and determines the final rendered color of the hyperlink.

Calculate Specificity Vectors for Rules A, B, and C: Specificity vector format: (a, b, c, d) where:

  • a = Inline styles
  • b = Number of ID selectors
  • c = Number of class, attribute, and pseudo-class selectors
  • d = Number of element and pseudo-element selectors
  • Rule A: #top-nav .nav-btn a
    • Inline: 0
    • IDs: 1 (#top-nav)
    • Classes: 1 (.nav-btn)
    • Elements: 1 (a)
    • Specificity vector = (0, 1, 1, 1) -> Value score = 1100 + 110 + 1*1 = 111
  • Rule B: nav.navbar a.primary
    • Inline: 0
    • IDs: 0
    • Classes: 2 (.navbar, .primary)
    • Elements: 2 (nav, a)
    • Specificity vector = (0, 0, 2, 2) -> Value score = 210 + 21 = 22
  • Rule C: #cta-link
    • Inline: 0
    • IDs: 1 (#cta-link)
    • Classes: 0
    • Elements: 0
    • Specificity vector = (0, 1, 0, 0) -> Value score = 1*100 = 100

Evaluate Cascade Precedence: Comparing Rules A, B, and C:

  • Rule B has 0 IDs, so it is eliminated by Rules A and C.
  • Rule A (0, 1, 1, 1) beats Rule C (0, 1, 0, 0) because both have 1 ID, but Rule A has 1 class and 1 element selector.

However, Rule D is declared directly on the element via the style="..." attribute:

  • Rule D specificity vector = (1, 0, 0, 0) (Score = 1000).

Because inline styles possess higher specificity than any external or internal selector rule (unless an external rule applies !important), Rule D supersedes Rules A, B, and C.

Answer:

Specificity vectors:

  • Rule A: (0, 1, 1, 1) (Score = 111)
  • Rule B: (0, 0, 2, 2) (Score = 22)
  • Rule C: (0, 1, 0, 0) (Score = 100)
  • Rule D (Inline): (1, 0, 0, 0) (Score = 1000)

Rule D wins due to inline style precedence, rendering the link in purple. If Rule D were removed, Rule A would win with specificity (0, 1, 1, 1), rendering it in blue.


Exercises

Practice Exercises — Introduction to Web Architecture

Question 1

Define the terms Safety and Idempotence in the context of HTTP methods. Classify GET, POST, PUT, and DELETE under both criteria, and explain why choosing the correct method is critical for web caches and web proxies.

Definitions of Safety and Idempotence:

  • Safe Methods: HTTP methods that do not alter the server's resource state. They perform read-only queries and produce zero server-side side effects (except harmless logging and analytics).
  • Idempotent Methods: HTTP methods where executing the exact same request once produces the identical resource state on the server as executing it multiple times consecutively: f(f(x)) = f(x).

Classification of Core HTTP Methods:

  • GET: Safe: YES, Idempotent: YES. Retrieving data does not modify server state; repeating GET produces identical server state.
  • POST: Safe: NO, Idempotent: NO. Creates new child resources or triggers transactions. Repeating POST results in duplicate orders, duplicate bank deductions, or duplicate records.
  • PUT: Safe: NO, Idempotent: YES. Replaces the entire target resource with the request body. Sending the exact same replacement payload ten times leaves the resource identical to sending it once.
  • DELETE: Safe: NO, Idempotent: YES. Removes the target resource. Once deleted, subsequent identical DELETE requests find the resource already gone, leaving the server state unchanged.

Significance for Caches and Web Proxies: Web proxies and browser caches automatically cache responses to safe (GET/HEAD) requests, drastically conserving network bandwidth and reducing server workload. Furthermore, network proxies and browsers can safely auto-retry failed idempotent requests (GET, PUT, DELETE) upon transient TCP connection drops without user risk. In contrast, non-idempotent requests (POST) must never be retransmitted automatically without user confirmation, preventing duplicate billing or double submissions.

Answer:

Safe methods (GET) produce zero state changes; idempotent methods (GET, PUT, DELETE) produce identical server state whether executed once or repeatedly. Proxies cache safe methods and auto-retry idempotent requests upon network drops, whereas non-idempotent methods (POST) can never be retried automatically without risk of duplicate side effects.

Question 2

Explain the step-by-step sequence of the Critical Rendering Path (CRP) in modern web browsers. Distinguish between Layout (Reflow) and Painting (Repaint), and state which CSS properties trigger each.

Steps of the Critical Rendering Path:

  1. DOM Construction: HTML parser converts raw bytes to characters, tokens, and nodes, assembling the Document Object Model tree.
  2. CSSOM Construction: CSS parser processes stylesheets into the CSS Object Model tree. This operation blocks rendering until complete.
  3. Render Tree Generation: Intersects DOM and CSSOM to build visible nodes requiring display. Nodes styled with display: none and <head> tags are omitted.
  4. Layout (Reflow): Computes geometry (exact position coordinates, width, and height) for every box within the viewport.
  5. Paint (Repaint): Converts render nodes into visual pixels (drawing text, borders, colors, background images).
  6. Compositing: Assembles painted GPU layers into final screen output.

Reflow vs. Repaint:

  • Layout (Reflow): Occurs when geometric or structural properties change, forcing the browser to recalculate the positions and sizes of affected elements and all their descendants/siblings. Highly CPU-intensive. Triggered by changes to: width, height, padding, margin, font-size, display, position, top, left.
  • Painting (Repaint): Occurs when visual appearance changes without altering element geometry or layout footprint. Cheaper than reflow. Triggered by changes to: color, background-color, visibility, box-shadow, border-color.
  • Performance Best Practice: Animate only composite-layer properties handled directly by the GPU: transform and opacity.
Answer:

The CRP follows: DOM -> CSSOM -> Render Tree -> Layout -> Paint -> Composite. Layout (Reflow) recalculates geometric sizes and positions (triggered by width, margin, display), whereas Paint (Repaint) redraws visual styling without changing geometry (triggered by color, background-color).

Question 3

Why are semantic HTML5 elements preferred over generic <div> tags? List any five semantic structural elements introduced in HTML5 and describe their intended roles in a web document.

Reasons for Preferring Semantic Elements:

  1. Accessibility (a11y): Screen readers use semantic landmarks to provide shortcut keyboard navigation for visually impaired users.
  2. Search Engine Optimization (SEO): Search crawlers weigh <main> and <article> content higher than boilerplate navigation or footers.
  3. Maintainability and Developer Ergonomics: Self-describing element tags eliminate nested "div soup", accelerating code reviews and team collaboration.
  4. Consistent Browser Default Styles: Certain semantic tags provide standardized native keyboard focus and interaction behavior.

Five Semantic Structural Elements and Roles:

  1. <header>: Encapsulates introductory content, site branding, logo, search bar, and primary navigation wrappers.
  2. <nav>: Designates an explicit navigation section containing major site hyperlinks.
  3. <main>: Encloses the dominant, unique content of the document. Only one visible <main> element may exist per page.
  4. <article>: Defines an independent, self-contained composition intended for standalone distribution (such as a blog post or news article).
  5. <footer>: Contains metadata about the enclosing section or page, including author attribution, copyright statements, and terms of service.
Answer:

Semantic HTML5 tags improve screen-reader accessibility, SEO indexing, and code maintainability compared to generic <div> tags. Five core elements include <header> (introductory branding), <nav> (navigation links), <main> (central unique page content), <article> (self-contained distributable article), and <footer> (closing legal and author metadata).

Question 4

Explain how the Bootstrap 12-column grid system works. What is the functional role of the .container, .row, and .col-* classes, and why must columns always be immediate children of rows?

Structure and Operation of the 12-Column Grid: Bootstrap divides every horizontal row into 12 proportional virtual column slices. Developer classes specify how many of these 12 slices a child box spans across responsive breakpoint tiers (e.g., .col-12 spans 100% width, .col-6 spans 50% width, .col-4 spans 33.33% width). If the total column count in a row exceeds 12, the extra columns automatically wrap onto a new line.

Functional Roles of the Core Grid Containers:

  • .container / .container-fluid: Provides horizontal padding to prevent content from touching the viewport edge and centers the layout on widescreen displays using margin-left: auto; margin-right: auto;.
  • .row: Serves as a flexbox container (display: flex; flex-wrap: wrap;). Crucially, rows apply negative horizontal margins (e.g., -15px on left and right) to neutralize the internal padding of the surrounding .container.
  • .col-*: Provides horizontal padding (gutters) to keep column text from colliding.
  • Why columns must be immediate children of rows: The negative margins of the .row and the positive padding of the .col are mathematically matched. Placing non-column elements directly inside a row, or placing columns outside a row, breaks gutter alignment and causes horizontal overflow scrollbars.
Answer:

Bootstrap's grid partitions horizontal space into 12 flexible columns. Containers provide outer padding, rows apply negative margins to align content, and columns contain gutter padding. Columns must be immediate children of rows so that row negative margins and column positive padding cancel out perfectly, preventing broken layout gutters and horizontal scrolling.

Question 5

Differentiate between HTTP/1.1, HTTP/2, and HTTP/3 with respect to transport protocol, multiplexing, and Head-of-Line (HoL) blocking.

HTTP/1.1 Characteristics:

  • Transport: TCP.
  • Protocol Format: Plaintext text-based protocol.
  • Multiplexing: None. Supports persistent connections (keep-alive) and pipelining, but requests over a connection must be answered strictly in FIFO order.
  • Head-of-Line (HoL) Blocking: Severe application-layer HoL blocking; a slow or heavy server response stalls all subsequent queued requests behind it on that TCP connection.

HTTP/2 Characteristics:

  • Transport: TCP.
  • Protocol Format: Binary framing layer (headers and data frames).
  • Multiplexing: Full bidirectional multiplexing over a single shared TCP connection; requests and responses are interleaved simultaneously. Includes HPACK header compression.
  • Head-of-Line (HoL) Blocking: Eliminates application-layer HoL blocking. However, it introduces transport-layer TCP HoL blocking: because all streams share a single TCP socket, an OS-level TCP packet drop stalls all interleaved streams until retransmitted.

HTTP/3 Characteristics:

  • Transport: QUIC over UDP.
  • Protocol Format: Binary framing with integrated TLS 1.3 cryptographic security.
  • Multiplexing: Native stream multiplexing managed directly within the QUIC protocol.
  • Head-of-Line (HoL) Blocking: Completely eliminated. A dropped UDP packet affects only the specific stream containing that packet; all other concurrent streams continue processing uninterrupted.
Answer:

HTTP/1.1 uses plaintext over TCP with severe application-layer HoL blocking. HTTP/2 uses binary multiplexing over TCP, eliminating application HoL blocking but remaining vulnerable to TCP packet-loss HoL blocking. HTTP/3 runs QUIC over UDP, providing true independent multiplexing where packet loss on one stream never stalls other streams.

JavaScript and Client-Side Programming →