Explore
WEBSTER / SOFTWARE ENGINEERING← Senior DeveloperEducational reference · continually evolving

Chapter 06 / 15 · Webster International

Modern Websites & Frontend Engineering

HTML, CSS, JavaScript, React, rendering strategies, accessibility, performance, responsive systems and interaction design.

← Complete index

The big idea

The browser is a complete application runtime with a document tree, layout engine, JavaScript event loop, accessibility tree and network client.

01 / FIELD NOTE

What happens when a website loads

A navigation is a dependency graph, not one download: DNS resolves an origin, TCP/TLS or QUIC establishes transport, HTTP returns bytes, HTML parsing constructs DOM nodes, CSS builds style information, and layout/paint create pixels. Scripts can block parsing or occupy the main thread. Distinguish server response time, render-blocking resources, image discovery and post-load interaction latency; they require different fixes. Use Network waterfalls plus Performance traces rather than treating a single 'load time' as the cause.

Why it matters

A CRM dashboard can receive HTML quickly yet remain unusable while JavaScript hydrates; an image-heavy news page can show controls quickly but delay its largest visible image. Understanding the exact pipeline identifies the responsible team and change.

In practice

Scenario A — A Collingwood headlines page has a slow LCP: inspect the LCP element, response timing, preload discovery and image transfer before compressing unrelated icons. Scenario B — A calendar freezes after initial paint: record a main-thread trace and find an expensive synchronous event aggregation, rather than buying a faster server. Trade-off: preloading everything competes for bandwidth; prioritize only genuinely critical resources.

Browser DevTools console · illustrative
const nav = performance.getEntriesByType('navigation')[0];
if (nav) console.table({
  dnsMs: nav.domainLookupEnd - nav.domainLookupStart,
  connectMs: nav.connectEnd - nav.connectStart,
  responseMs: nav.responseEnd - nav.responseStart,
  domReadyMs: nav.domContentLoadedEventEnd - nav.startTime
});
// These timings are diagnostic, not a complete LCP or INP measurement.
Hands-on exercise · reveal the verification check
Try it

Open a page with DevTools Network and Performance. Record document status, a render-blocking resource, LCP element, and the longest main-thread task. Repeat with JavaScript disabled.

Check your result

Produce two observations with evidence: the HTML and key content remain readable without JS, and the measured bottleneck is assigned to network, rendering or scripting. Explain why an unrelated image optimization would not fix a long JS task.

02 / FIELD NOTE

HTML is structure; CSS is presentation; JS is behaviour

HTML describes meaning and native behavior, CSS describes presentation, and JavaScript coordinates changes. A link navigates, a button invokes an action, and a form submits named controls; these semantics already connect keyboard, focus, browser history and assistive technology. CSS Grid and Flexbox express layout without changing reading order. Enhance a working HTML baseline instead of rebuilding every control from div elements.

Why it matters

A reusable 'button' component with no native keyboard behavior creates defects in every dashboard. Correct semantics reduce custom code, make automation reliable and preserve a usable fallback if scripts fail.

In practice

Scenario A — In a dog-walking CRM, 'View invoice' is an anchor with a real href, while 'Mark paid' is a button requiring a server authorization check. Scenario B — A venue search is a labeled GET form whose query is shareable in the URL; CSS makes its fields compact on desktop and stacked on mobile. Trade-off: native elements have browser styling differences, but replacing them with custom widgets incurs substantial accessibility and maintenance costs.

HTML · illustrative standalone form
<form action="/search" method="get">
  <label for="town">Town</label>
  <input id="town" name="town" autocomplete="address-level2">
  <button type="submit">Find events</button>
</form>
<a href="/invoices/123">View invoice</a>
<button type="button" id="mark-paid">Mark paid</button>
<!-- The action button needs an authenticated server request handler. -->
Hands-on exercise · reveal the verification check
Try it

Build one native search form, a navigation link and an action button. Tab through them, submit with Enter, and test without JavaScript.

Check your result

The label focuses the input; Enter submits a GET request with ?town=...; the link navigates; the action button does not navigate. Keyboard focus remains visible and server actions still check authorization.

03 / FIELD NOTE

Components, state and data flow

Treat component state as a minimal set of facts, not a second database. Keep the canonical collection, selected identifier and user-entered filters; compute visible records from those inputs. Events request state transitions, rendering derives output, and effects synchronize with external systems. Avoid duplicated totals, filtered arrays and selected objects that can disagree after a fetch or edit. Separate server cache from ephemeral UI state and use stable record IDs.

Why it matters

A route planner can show seven map pins but eight list entries when both maintain separate mutable copies. Derived views keep map, list and statistics consistent from one source of truth.

In practice

Scenario A — A music directory stores artists and a genre filter; a filtered count is derived each render, not incremented manually. Scenario B — A dog booking editor stores booking IDs and a pending edit, then revalidates the server revision before confirming changes. Trade-off: computing a huge derived view every keystroke may require indexing or memoization, but memoization is a performance optimization, not another source of truth.

JavaScript (Node 18+) · runnable
const assert = require('node:assert/strict');
const artists = [{id:1,genre:'funk'},{id:2,genre:'jazz'},{id:3,genre:'funk'}];
const state = {artists, genre:'funk'};
const visible = s => s.artists.filter(a => a.genre === s.genre);
assert.deepEqual(visible(state).map(a => a.id), [1,3]);
state.genre = 'jazz';
assert.deepEqual(visible(state).map(a => a.id), [2]);
console.log('Derived list stays in sync');
Hands-on exercise · reveal the verification check
Try it

Model a three-stop route list and a selected client ID. Reorder the stops and derive numbered map pins and the selected client from the same records.

Check your result

After moving stop 3 to position 1, map and list both read 1,2,3 in the new order; the selected client remains the same ID. No separately stored 'visiblePins' array is required.

04 / FIELD NOTE

Server rendering, static rendering and client rendering

Static generation writes HTML before requests, server-side rendering creates HTML for each request, and client rendering builds or updates UI after scripts execute. Hydration attaches event handlers to server HTML; the initial client tree must match the server output. Choose rendering by route and content freshness, not framework fashion. Make important reading and navigation available in HTML, then progressively enhance interactive portions.

Why it matters

Search engines, assistive technology, low-end phones and intermittent connections benefit from meaningful initial HTML. A personalized dashboard may require request-time authorization, while a public engineering chapter rarely does.

In practice

Scenario A — Publish a static guide with all headings, examples and links visible when its bundle returns 404; add copy/search features when JS loads. Scenario B — Render a logged-in booking summary on the server and hydrate its drag-and-drop controls, but never embed another user's records in shared cached HTML. Trade-off: SSR increases server work and hydration complexity; static HTML reduces cost but needs revalidation for freshness.

HTML · illustrative progressive enhancement
<main>
  <h1>Upcoming concerts</h1>
  <ol><li><a href="/events/42">Jazz at the Hall</a></li></ol>
</main>
<script src="/assets/event-filters.js" defer></script>
<!-- With JavaScript blocked, the list and event link still work. -->
Hands-on exercise · reveal the verification check
Try it

For a public article and a private CRM route, choose static, server or client rendering. Simulate a 404 for the enhancement bundle.

Check your result

The article body and canonical links remain usable without JS. The CRM route checks authentication server-side and never leaks personalized HTML through a public cache. Explain how you would detect hydration mismatch.

05 / FIELD NOTE

Responsive design and mobile-first interaction

Responsive design is an information-priority problem: the viewport, component container, text zoom, pointer precision and reading order all matter. Use fluid layouts and container queries where a card must adapt to its actual panel width. Preserve source order when CSS reflows content; do not rely on drag-only or hover-only actions. Distinguish WCAG 2.2 SC 2.5.8's 24×24 CSS-pixel minimum with exceptions from a larger ergonomic target you may choose for touch-heavy interfaces.

Why it matters

A dense route planner needs an editable ordered list at 390px and a side-by-side map at 1440px without hiding keyboard reorder controls or forcing horizontal scrolling.

In practice

Scenario A — A CRM map panel switches from split columns to a stacked layout when its container narrows, not just when the entire viewport narrows. Scenario B — A musician card displays summary and action links in a narrow drawer; on desktop it adds metadata without changing the logical focus order. Trade-off: larger targets and generous spacing reduce density; expose a user-controlled compact mode only if minimum target spacing and focus remain usable.

CSS · illustrative
.route-panel { container-type: inline-size; }
.route-layout { display: grid; gap: 1rem; }
.route-action { min-width: 2.75rem; min-height: 2.75rem; }
@container (min-width: 45rem) {
  .route-layout { grid-template-columns: minmax(16rem, 1fr) minmax(20rem, 2fr); }
}
/* Keep list and map in a logical DOM order; provide move-up/down buttons. */
Hands-on exercise · reveal the verification check
Try it

Create a route list with map and up/down buttons; test at 390px, 1440px and 400% zoom.

Check your result

No two-dimensional page scroll is required for the list; each stop can move by keyboard; map remains supplementary rather than the only way to understand order; target dimensions/spacing satisfy the chosen criterion.

06 / FIELD NOTE

Accessibility is an architecture concern

Accessibility is a contract across component markup, interaction state and application routing. The accessibility tree exposes roles, names and states; keyboard focus must follow a coherent task flow. A modal dialog must move focus inside, keep background interaction inert while open, support Escape where appropriate and restore focus logically on close. Status messages must be conveyed without stealing focus. Test native semantics before adding ARIA; ARIA annotations do not implement behavior.

Why it matters

A flawed shared modal or combobox can make every booking and invoice workflow inaccessible. Building the interaction correctly once prevents repeated remediation and makes regression tests meaningful.

In practice

Scenario A — Opening a booking dialog focuses its heading or first field, traps Tab inside, closes with Escape and returns to the trigger. Scenario B — A map optimization completes asynchronously; the ordered stop list updates and a polite status reports 'Route updated' without forcing focus away from the current stop. Trade-off: a native dialog can simplify modality, but focus placement, cancellation semantics and form errors still need product-specific decisions.

HTML + browser JavaScript · illustrative
<button id="open" type="button">Edit booking</button>
<dialog id="editor" aria-labelledby="edit-title">
  <h2 id="edit-title">Edit booking</h2>
  <form method="dialog"><button type="submit">Close</button></form>
</dialog>
<script>
  const opener = document.querySelector('#open');
  const dialog = document.querySelector('#editor');
  opener.addEventListener('click', () => dialog.showModal());
  dialog.addEventListener('close', () => opener.focus());
</script>
Hands-on exercise · reveal the verification check
Try it

Implement a booking modal with title, close control and a validation error. Test Tab, Shift+Tab, Escape and returning focus.

Check your result

Focus begins within the modal, cannot enter background controls while open, and returns to the opener on close. Error text is associated with its field; the title is announced and background content is not incorrectly aria-hidden.

07 / FIELD NOTE

Performance, images and caching

Performance is a budget across transfer, decoding, layout, scripting and cache freshness. Optimize for user journeys with field data (LCP, INP, CLS) and use lab traces to explain causes. Give images explicit dimensions, appropriate responsive sources and descriptive alternatives. Prioritize the true LCP image, lazy-load below-fold media and defer non-critical embeds. Fingerprinted static assets may be cached long-term; HTML and personalized API responses need different freshness and privacy policies.

Why it matters

A jazz showcase with thirty embedded videos can overwhelm mobile bandwidth and main-thread time even when its HTML is small. A CRM route map may spend more time laying out markers than fetching data.

In practice

Scenario A — Load a featured artist poster at the required display size, reserve its dimensions and use a click-to-load video facade for secondary embeds. Scenario B — A dashboard ships a versioned JS bundle with long-lived caching while its private booking API uses no-store; measure how often the UI shows stale data. Trade-off: aggressive caching saves bandwidth but risks stale resources without hashed filenames or invalidation.

HTML · illustrative media policy
<img src="/media/artist-640.webp"
     srcset="/media/artist-320.webp 320w, /media/artist-640.webp 640w"
     sizes="(max-width: 600px) 90vw, 640px"
     width="640" height="400" alt="Artist playing bass on stage"
     fetchpriority="high">
<!-- Use loading="lazy" on below-fold images, not the LCP hero. -->
Hands-on exercise · reveal the verification check
Try it

Audit a page with a hero image, ten posters and three videos. Set a transfer budget, record LCP/INP/CLS, and change one media-loading strategy.

Check your result

Before/after traces identify the same viewport and connection conditions. Hero dimensions are reserved, secondary embeds are deferred, and the change improves a measured bottleneck without hiding essential content.

08 / FIELD NOTE

Forms, validation and optimistic updates

A form is a state machine: idle → validating → pending → confirmed or failed/conflicted. Client-side constraints improve feedback but do not authorize or validate server writes. Fetch resolves on HTTP error responses, so inspect response.ok and status; distinguish network failure, 401/403, 409 conflicts and validation errors. Optimistic updates are provisional until server confirmation, and must roll back or reconcile on failure. Use idempotency keys for retry-prone creates when supported by the API.

Why it matters

A dog-walking booking should never display 'Saved' just because a click handler ran. Users need truthful persistence feedback and a recoverable path when another staff member changes the same appointment.

In practice

Scenario A — A client updates a booking based on revision 7; the server returns 409 because revision 8 exists, so show the latest value and preserve the unsent edit. Scenario B — A callback form loses connectivity; keep its draft, announce the failure, and offer retry without creating duplicate requests. Trade-off: optimistic UI feels immediate but increases reconciliation complexity; pessimistic confirmation is simpler for high-risk actions.

JavaScript (browser) · illustrative
async function saveBooking(payload, revision, signal) {
  const response = await fetch('/api/bookings/42', {
    method: 'PUT', credentials: 'same-origin', signal,
    headers: {'Content-Type':'application/json', 'If-Match': String(revision)},
    body: JSON.stringify(payload)
  });
  if (response.status === 409 || response.status === 412) throw Error('Conflict: reload and compare');
  if (!response.ok) throw Error('Save failed: HTTP ' + response.status);
  return response.json();
}
// Server must enforce authorization, validation and revision preconditions.
Hands-on exercise · reveal the verification check
Try it

Mock save responses 200, 409, 422 and a rejected network request. Design UI states and retry behavior for each.

Check your result

200 confirms persistence; 409 preserves edits and offers conflict resolution; 422 shows field errors; network failure retains a draft and never claims 'Saved'. A second click cannot silently duplicate the write.

09 / APPLIED RESEARCH

Build a resilient loading-state system

Model loading, success, empty, stale and error as explicit UI states. Use skeletons only when content shape is predictable and offer recoverable actions rather than trapping a page behind perpetual progress animation.

Why it matters

Network requests fail and partial data is normal; UI correctness includes absence of data.

In practice

An artist search returns zero records: show 'No artists found', a clear filters button and a date of last successful refresh.

Hands-on exercise · reveal the verification check
Try it

Design a five-state component for event listings.

Check your result

Test slow network, timeout, error, empty and success.

10 / APPLIED RESEARCH

Core Web Vitals: measure actual user experience

Measure Largest Contentful Paint for loading, Interaction to Next Paint for responsiveness, and Cumulative Layout Shift for stability. Google's good thresholds are LCP at most 2.5s, INP at most 200ms, CLS at most 0.1, measured at the 75th percentile.

Why it matters

Animations and dozens of embeds may look impressive while delaying real interactions.

In practice

Lazy-load YouTube iframes, reserve poster dimensions and profile the search filter's longest tasks.

Hands-on exercise · reveal the verification check
Try it

Measure a page with mobile throttling before changing code.

Check your result

Record LCP, INP and CLS for before and after release.

11 / APPLIED RESEARCH

Accessible modals, drawers and focus management

Use native dialog where suitable or implement a consistent modal contract: label, visible close, focus inside, Escape close, inert background and restore focus to opener. Keep informational sidebars nonmodal when they shouldn't trap focus.

Why it matters

Keyboard and screen-reader navigation must match visual behaviour.

In practice

An engineering guide drawer opens from the left; its search gets focus and the trigger receives focus after close.

Hands-on exercise · reveal the verification check
Try it

Open and close a drawer using only Tab, Shift+Tab and Escape.

Check your result

Focus never escapes during modal operation and is restored.

12 / APPLIED RESEARCH

Responsive content density as information architecture

Choose what matters at each viewport: desktop can show filters, headlines and calendar; mobile should preserve source, town, date and critical actions in a scannable stack. Let users choose expanded details rather than rendering all metadata at once.

Why it matters

Mobile design is about prioritisation, not a scaled-down desktop screenshot.

In practice

Show event date, artist, venue and source in a compact row, expanding to address and tickets on demand.

Hands-on exercise · reveal the verification check
Try it

Sketch 320, 390, 768 and 1440px states for an event grid.

Check your result

Every primary action is visible without hover or horizontal scrolling.

13 / APPLIED RESEARCH

Hydration failures and progressive enhancement

When JavaScript enhances server-rendered HTML, the original content should remain meaningful if bundles fail. Avoid replacing a useful page with an empty mount until modules finish. Use predictable DOM anchors and progressively attach interactivity.

Why it matters

Users can receive HTML 200 while scripts are 404, breaking every lesson and internal link.

In practice

Embed article bodies and chapter anchors directly in HTML; let search, drawer and number converter enhance them.

Hands-on exercise · reveal the verification check
Try it

Disable JavaScript and open a content-heavy page.

Check your result

All headings, anchors, articles and source links remain usable.

14 / APPLIED RESEARCH

Images, video embeds, and content provenance

Store alt text, source URL, permissions, width/height and optional credit with media metadata. Prefer responsive images and lazy-load third-party embeds after an explicit interaction when they are heavy or tracking-sensitive.

Why it matters

Image-rich directories need both discoverability and good performance without broken fallbacks.

In practice

An artist card uses a small WebP cover with correct dimensions; video playback begins only inside detail view.

Hands-on exercise · reveal the verification check
Try it

Audit 10 media cards for dimensions, alt text, fallback and provenance.

Check your result

No broken URLs, layout shifts or unattributed third-party assets.

Rendering

15 / FIELD NOTE

Critical rendering path: DOM, CSSOM, layout, paint and compositing

Browsers transform HTML and CSS into a document tree and style model, then compute layout, paint pixels and composite layers. A slow page may be waiting for network resources, JavaScript, fonts or repeated layouts; these causes require different remedies.

Why it matters

Optimizing rendering begins with observing where time is actually spent.

In practice

Record a Performance trace for an event directory, reserve image dimensions and compare first render with and without render-blocking scripts.

HTML
<script src="/assets/main.js" defer></script>
<img src="cover.webp" width="400" height="400" loading="lazy" alt="Album cover">
Hands-on exercise · reveal the verification check
Try it

Capture a mobile performance trace and identify the largest task.

Check your result

Name the bottleneck and the effect of one measured change.

16 / FIELD NOTE

Accessible dialogs, forms and the browser accessibility tree

Native semantic elements expose roles, names and state to assistive technology. Labels, focus order, keyboard access, live announcements and error messages must match what visual users see. Modal dialogs require deliberate focus containment and restoration; nonmodal sidebars should not trap focus.

Why it matters

A polished UI can still be impossible to use without a mouse.

In practice

Implement a calendar edit dialog with field labels, validation summary, Escape close and focus restoration.

Accessible HTML
<label for="event">Event</label>
<input id="event" aria-describedby="event-help">
<p id="event-help">Enter the public event title.</p>
Hands-on exercise · reveal the verification check
Try it

Test the dialog using keyboard and screen reader.

Check your result

All errors and actions can be discovered without a pointer.

17 / FIELD NOTE

SSR, static HTML, hydration and failed-bundle resilience

Server rendering supplies readable initial HTML, static generation prebuilds output, hydration attaches interactivity and client-only rendering waits for JavaScript. Progressive enhancement preserves essential reading and links when network scripts fail; mismatched initial state can cause hydration errors.

Why it matters

Content should remain accessible even when one deployment asset returns 404.

In practice

Keep the engineering guide chapter text in HTML, attaching search and code-copy enhancements only after scripts load.

Hands-on exercise · reveal the verification check
Try it

Disable JavaScript and block one module request.

Check your result

All lessons and source links remain readable.

18 / FIELD NOTE

Responsive dashboards: container queries and touch-safe interactions

Responsive work prioritizes user tasks, not merely reducing widths. Grid, Flexbox and container queries can reorganize dense content according to available space; touchscreens need visible controls rather than hover-only functionality. Keyboard and reduced-motion users need equivalent actions.

Why it matters

Map cards, artist galleries and schedules must remain navigable on narrow screens.

In practice

Let a full-screen artist card swipe on mobile while preserving accessible Next/Previous buttons and source links.

CSS
.cards { display: grid; grid-template-columns: repeat(auto-fit,minmax(min(100%,20rem),1fr)); gap:1rem; }
Hands-on exercise · reveal the verification check
Try it

Test 320, 390, 768 and 1440 pixel layouts.

Check your result

Critical actions work with touch and keyboard without horizontal scrolling.

19 / FIELD NOTE

Server cache versus URL state versus optimistic UI state

The URL describes sharable filters, local component state holds temporary interactions, server caches hold fetched results and the database remains authoritative. Optimistic mutations must rollback or reconcile when rejected and must not masquerade as committed bookings.

Why it matters

Duplicated sources of truth produce stale pages and misleading confirmations.

In practice

Put calendar view filters in URL parameters, draft edits in local state and final booking availability in the server.

JavaScript
const params = new URLSearchParams(location.search);
const town = params.get('town') ?? 'all';
Hands-on exercise · reveal the verification check
Try it

Simulate a failed optimistic booking mutation.

Check your result

The UI restores the actual server state.

20 / FIELD NOTE

Performance budgets: media, LCP, INP and CLS

Largest Contentful Paint measures loading, Interaction to Next Paint measures responsiveness and Cumulative Layout Shift measures stability. Reserve poster dimensions, lazy-load below-the-fold content, constrain third-party scripts and initialize video players only when needed.

Why it matters

A music site with hundreds of embeds may look rich but feel broken under real mobile conditions.

In practice

Load album thumbnails first and mount the selected YouTube player after activation, recording before/after network cost.

HTML
<img src="artist.webp" width="320" height="320" loading="lazy" decoding="async" alt="">
Hands-on exercise · reveal the verification check
Try it

Measure a 30-card gallery under throttled network and CPU.

Check your result

Compare responsiveness and total bytes before and after changes.