What you'll learn: By the end of this lesson you will be able to say what HTML, CSS and JavaScript each own in a large interface, apply the rule of least power to decide which layer should solve a problem, explain how scripts and stylesheets block parsing and rendering and which loading attributes change that, keep the three layers decoupled with hooks, custom properties and cascade layers, describe progressive enhancement as a baseline plus enhancements, and spot the common ways the layers get tangled together.
Think of a house. The walls and rooms are the structure, the paint and furniture layout are the look, and the wiring and plumbing are the behaviour. A good builder can repaint a room without rewiring it, and a power cut does not make the walls disappear. A web page has the same three concerns, and the browser gives each one its own language: HTML for structure and meaning, CSS for presentation, JavaScript for behaviour. Most "large interface" problems are cases where one layer has quietly taken over another one's job, so that repainting means rewiring.
The running example is the product page of a grocery marketplace (the front end of the ShopStream marketplace used in this course): a title, a photo gallery, a price, an "Add to basket" control, a list of reviews with a "Show more" button, and a site header with navigation. It is an ordinary page that every team has built, which is exactly why it shows where the layers blur.
The core idea
- Each language has a job. HTML says what things are (a heading, a link, a button, a list). CSS says how they look and where they sit. JavaScript says what happens when something changes. A layer that does another layer's job costs more and breaks more.
- Pick the least powerful tool that works. The W3C TAG's finding "The Rule of Least Power" says to use the least powerful language suitable for expressing information, constraints or programs on the web, because powerful languages inhibit information reuse and are usually harder to secure. In a page that means: if a native element does it, use the element; if a CSS rule does it, use CSS; reach for a script last.
- Build up from a baseline. MDN defines progressive enhancement as providing a baseline of essential content and functionality to as many users as possible, while delivering the best possible experience only to users of the most modern browsers that can run all the required code. HTML is the baseline, CSS and JavaScript are the enhancements.
This lesson is about the architecture around those three ideas: who owns what, how the files are loaded, and how the layers talk to each other without knowing too much about each other. The detail of semantic markup, CSS methodologies and layout has lessons of its own (Semantic HTML and Document Structure, CSS Architecture and Scaling, Modern CSS Layout, all in this module); here you get the map.
Three layers, three jobs
| Layer | Owns | Does not own | Example on the product page |
|---|---|---|---|
| HTML | Content, structure, meaning, built-in behaviour (links, forms, buttons) | Colours, spacing, animation | A heading for the product name, a button for "Add to basket" |
| CSS | Presentation, layout, responsive rules, states that selectors can express | Whether content exists, what a control does | A two-column layout on wide screens, a focus ring on controls |
| JavaScript | Behaviour that needs computation, state or the network | Basic navigation, basic form submission, styling decisions | Updating the basket count without a full page load |
The table is a guide, not a wall. A script can change a class and CSS can generate content, but each crossing has a price: a style set by a script is harder to override from a stylesheet, and content that exists only in a stylesheet is not part of the document structure. The question to ask is "which layer is the natural owner?" and the answer is usually the least powerful one that can do the job.
Figure 1. The three layers and what flows between them
How to read this: the in-memory document is the meeting point. HTML builds it, CSS decorates it and JavaScript edits it. The layers never call each other directly; they meet in the document, which is why the hooks you leave in the markup matter.
Illustration 1: the minimal example
The smallest useful split is one control with each layer doing its own part. This markup is an illustration, not a lab, and no output is claimed for it:
<form action="/basket/items" method="post">
<input type="hidden" name="productId" value="p-1042">
<button type="submit" class="add-to-basket">Add to basket</button>
</form>
.add-to-basket { padding: 0.6rem 1rem; }
.add-to-basket:focus-visible { outline: 3px solid currentColor; }
document.querySelector(".add-to-basket").form.addEventListener("submit", (event) => {
event.preventDefault();
// send the request with fetch, then update the basket count
});
HTML alone gives a working feature: a button inside a form submits it, and MDN's button page says submit is the default type for a button associated with a form. CSS makes it look right and visible when focused. The script is an enhancement: it takes over the submit to avoid a full page load. If the script fails to load, the form still works. That ordering, working first and better second, is the architecture in miniature.
The layer boundary: who decides what
A decision tree helps in design reviews, because the question "should this be JavaScript?" comes up on every feature.
Figure 2. Which layer should solve it?
or attribute do it?"} A -->|"yes"| H["Use HTML
(link, form, button, details)"] A -->|"no"| B{"Is it appearance, layout
or a selector-able state?"} B -->|"yes"| C["Use CSS
(rules, media queries)"] B -->|"no"| D["Use JavaScript
(state, network, computation)"] D --> E["Keep the essential path
working without it"]
How to read this: the order is the rule of least power. Each step down is more flexible and more costly: more bytes, more main-thread time, more ways to fail, and more work for assistive technology to understand.
Three examples of the tree in use. A disclosure widget ("Show more reviews") starts as a native element if the HTML offers one for the job, and only becomes a scripted component if it needs behaviour the element cannot give. A responsive two-column layout is a media query, not a script that measures the window. A basket count that updates after a server round trip needs JavaScript because it needs the network.
How the browser consumes the three layers
Structure, style and script are three kinds of resource with different effects on the first paint. The deep treatment is in The Critical Rendering Path and How Browsers Work; here are the rules an architect needs when deciding how to split and load files.
Stylesheets block rendering
The web.dev guide to render-blocking CSS says that by default CSS is treated as a render-blocking resource. Media types and media queries let you mark some CSS as non-blocking: a stylesheet with media="print" is not render blocking when the page first loads, while one whose media query matches blocks rendering until it is downloaded and processed. The browser still downloads every stylesheet, with a lower priority for the non-blocking ones.
Architecturally this means the amount of CSS in the critical path is a budget. A single stylesheet for the whole application makes every page wait for rules it never uses; splitting by purpose (global, per route, print) lets the browser block only on what the first view needs.
Scripts block parsing, not rendering
MDN's script page says scripts without async, defer or type="module", and inline scripts without type="module", are fetched and executed immediately before the browser continues to parsing the page, and that such a script blocks parsing, not rendering. The attributes change that:
| Script form | Fetched | Runs | Order guaranteed? |
|---|---|---|---|
| Classic, no attribute | Immediately, parsing waits | Immediately | In document order, because parsing waits |
defer |
In parallel with parsing | After parsing, before DOMContentLoaded |
Yes, in document order |
async |
In parallel with parsing | As soon as it is ready | No |
type="module" |
In parallel with parsing | Deferred by default | In document order, like defer |
MDN also states that defer and async must not be used on inline scripts (no src), where they have no effect; that defer has no effect on module scripts because they defer by default; and that if async and defer are both given, the element acts as if only async were set. MDN notes that only scripts in the document head can block rendering and, for scripts added by other scripts, that blocking="render" is needed for that. This lesson does not go further into that attribute.
Figure 3. Parsing, fetching and running with and without defer
How to read this: the same bytes cost very different amounts of waiting. A classic script in the head stops the parser while it downloads and runs. A deferred script downloads during parsing and runs after it, in order.
The architectural consequence is that application code should usually be a module or a deferred script, so it never holds up the parser, and anything that must run earlier (for instance something that sets a state class on the document) should be tiny and inline.
Keeping the layers decoupled
When the layers meet in the document, the coupling happens through names: class names, attribute names, element names, custom property names. Decide those names on purpose.
Hooks for scripts. A script that finds elements by a styling class couples to the stylesheet: restyling the page by renaming a class silently breaks behaviour. A convention that avoids this is a separate hook for behaviour, commonly a data-* attribute. MDN describes data attributes as a way to store extra information on standard, semantic elements, read from JavaScript through the dataset property. MDN also warns not to store content that should be visible and accessible in data attributes, because assistive technology may not access it. Hooks and state, yes; user-facing text, no.
Custom properties as the style interface. CSS custom properties (names starting with two dashes) are set in a rule, read with var(), which takes an optional fallback, and a property defined that way always inherits its parent's value. They are also readable and writable from JavaScript, for example with element.style.setProperty. That makes them a clean interface between layers: CSS defines the design tokens (colours, spacing), and a script that needs to change the look sets a token rather than hard-coding values.
Cascade layers for ordering. The @layer at-rule declares layers whose order sets precedence. MDN says that once layer order is established, specificity and order of appearance are ignored between layers, that the last layer listed wins, and that styles not in a layer override layered normal styles. For !important the order reverses. Layers let a team say "resets, then components, then utilities" once, rather than win each fight with a more specific selector. MDN's specificity page gives the weights (an ID adds 1-0-0, a class, attribute selector or pseudo-class adds 0-1-0, a type selector or pseudo-element adds 0-0-1) and says :where() always contributes zero.
Custom elements for scripted components. MDN describes custom elements as HTML elements whose behaviour is defined by the developer: names must contain a hyphen, and customElements.define registers them. Autonomous ones inherit from HTMLElement and build their behaviour from scratch; customized built-in ones extend a standard element. MDN says setup is best placed in connectedCallback, called each time the element is added to the document, rather than in the constructor. For architecture, the point is a named boundary: the element's tag name in the markup is the contract, and its internals are free to change.
Illustration 2: the realistic example
The product page, with the layers set up deliberately. Again this is a structural sketch, not captured output:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fresh Basil, 100 g | ShopStream</title>
<link rel="stylesheet" href="/css/base.css">
<link rel="stylesheet" href="/css/product.css">
<link rel="stylesheet" href="/css/print.css" media="print">
<script type="module" src="/js/product.js"></script>
</head>
<body>
<header>...</header>
<main>
<h1>Fresh Basil, 100 g</h1>
<form action="/basket/items" method="post" data-enhance="add-to-basket">...</form>
<section aria-labelledby="reviews-heading">
<h2 id="reviews-heading">Reviews</h2>
...
</section>
</main>
</body>
</html>
Read it as an architecture. The structure is real HTML: a heading hierarchy, a form that works without a script, a labelled section. Styling is split by purpose, with print rules in a non-blocking stylesheet (per the web.dev guidance above). Behaviour is one module that finds data-enhance hooks, so renaming CSS classes cannot break it. Nothing the page needs to be understood is created only by script.
Components blur the layers
Modern component frameworks put markup, style and behaviour for one UI piece in one file or folder, and that is a sound architecture: the unit of separation moves from language to component. See Component-Based Architecture. The three-layer thinking still applies inside the component. A component's output is still HTML that a browser, a screen reader and a search crawler read; its styles still go through the cascade; its event handlers still run on the main thread. A component that produces div elements with click handlers instead of real controls has not separated concerns, it has hidden a missing baseline. How rendering strategies change where the HTML is made is in Rendering Strategies.
Progressive enhancement as an architecture, not a slogan
Applied to a large interface, progressive enhancement is a set of decisions made per feature:
- Define the baseline. What must work with markup and styles alone? Reading content and following links, submitting the main forms, reaching every page by URL.
- List the enhancements. Which features add value but are not essential: live updating, drag and drop, instant filtering?
- Decide the failure plan. Scripts can fail to download, be blocked, or throw. The baseline is what remains. A page whose only HTML is an empty container has no baseline; where that is a deliberate choice (some applications are inherently interactive), say so and plan for the failure differently.
Progressive enhancement does not forbid single-page applications. It is a question of how much of the first experience depends on a script, and the performance and SEO lessons (for example SEO Architecture for Front Ends and Core Web Vitals) show what that dependence costs.
Illustration 3: a failure, the fake button
A team builds the "Add to basket" control as a div with a click handler, styled with a class. It looks right in every review. In production the script bundle fails to load for some users (a blocked third-party host on the same bundle, say; the cause is not the point). Those users see a button that does nothing. A div has no built-in keyboard or control semantics, so a keyboard user or screen reader user gets nothing unless the team also added focus, key handling and a role by hand; with the script missing, even that is gone. MDN's a page makes the same point from the other side: anchors are often abused as fake buttons with href="#" and a click listener, and it advises using a button instead and keeping hyperlinks for navigation to a real URL.
Figure 4. The same page with and without the script
How to read this: the green path needs only the browser. The orange path hangs on a script; when the red box is missing, the click leads nowhere.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| One stylesheet for the whole app | Simple to cache and reason about | Every page waits for all of it |
| CSS split by route and purpose | Smaller critical path | More files, a loading strategy to maintain |
Behaviour hooks via data-* attributes |
Restyling cannot break scripts | One more convention to enforce |
| Cascade layers | Predictable ordering, fewer specificity fights | Teams must learn the rules, including the !important reversal |
| Custom elements | A named, framework-independent boundary | Lifecycle details and no server rendering by default |
| Native elements first | Free behaviour, accessibility, resilience | Less control over exact look and behaviour |
| Script-built UI | Maximum flexibility | Baseline, accessibility and performance become your job |
Build it
This lesson has no lab: its subject is how three languages divide a page, and no program of ours would say more than the pages cited below. The HTML, CSS and JavaScript above are structural sketches, shown without captured output, and none of it was run or measured. To see the loading rules for yourself, add defer to a script tag on a page of your own and compare when it runs relative to the DOMContentLoaded event in your browser's developer tools.
In practice: the marketplace product page
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The product page has grown for three years. Its stylesheet is one 300 KB file (illustrative) with selectors that fight each other; several rules use !important. A bundle in the document head loads without defer, so the page shows nothing until it is downloaded and run. The "Show more reviews" and basket controls are built from div elements. Support receives reports of a "dead" page from users on a slow network.
Starting architecture
Figure 5. One big file for each language, all in the critical path
How to read this: the warning boxes are where the layers are tangled and loaded in the most expensive way. First paint waits on the largest, least selective resources.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Minify and compress only | Fewer bytes | Little effort | Blocking and tangling remain |
| Split CSS by route, defer scripts, restore native controls | Critical path, resilience, accessibility | Refactor of markup and handlers | Regressions in untested interactions |
| Rewrite as a component framework app | A new unit of separation | Large effort, new failure modes | Same problems in new files if the layering is not decided |
The decision
| Field | Decision record |
|---|---|
| Context | A blocking script and one large stylesheet delay first paint, and key controls are not real controls. |
| Decision | Make application code a module loaded without blocking the parser. Split CSS into base, per route and print, with a cascade-layer order of reset, components and utilities. Replace div controls with a button and a form, enhanced by a script that finds data-enhance hooks. |
| Consequences, good | The baseline works without the script; the critical path shrinks; specificity fights end. |
| Consequences, bad | Several PRs of mechanical change, and a convention to enforce in review. |
| Revisit when | The page moves to server components or another rendering strategy that changes who produces the HTML. |
Rollout and verification
- List the baseline per page (read, navigate, add to basket) and test each with scripts disabled.
- Move one route first. Switch the script to a module, split that route's CSS, and compare field timings before and after with the tools from the Core Web Vitals lesson.
- Introduce layers gradually. MDN says unlayered styles override layered ones, so old unlayered rules keep winning over new layered ones until they are moved; plan the migration order with that in mind.
- Check keyboard and screen reader use for every control that changed.
The 2 a.m. failure
A CDN problem makes the script host return errors. Pages still load, but the basket button on the old markup does nothing, and support receives a flood of reports.
First three checks: (1) load the page with the script blocked and see which controls still work; (2) look at the network panel for the failed script and its initiator; (3) check whether the form fallback exists on the affected template. Mitigation: serve the script from a fallback host or roll back the template that removed the form. Follow-up: a test that loads each key page with the script blocked and asserts the baseline works.
Architect's notes
- Decide ownership per feature. The question "which layer should solve this?" costs seconds in review and saves months.
- Name your hooks. Classes are for styling,
data-*attributes or custom element names are for behaviour, custom properties are the style interface. - Treat critical-path CSS and blocking scripts as a budget the whole team shares.
- Baseline first. Decide what must work without the script, and test it.
- Components change the boundary, not the principle. What reaches the browser is still HTML, CSS and JavaScript.
Common mistakes
- Using a
divor an anchor withhref="#"as a button. - Selecting elements for behaviour by their styling classes.
- Winning style fights with
!importantor longer selectors instead of using layers or reducing specificity. - A classic script in the head with no
defer,asyncor module type. - Putting visible text in
data-*attributes. - Adding
deferorasyncto an inline script, where MDN says it has no effect. - Assuming scripts always load.
- Making CSS and JavaScript one concern because the framework puts them in one file.
Key takeaways
- HTML owns structure and meaning, CSS owns presentation, JavaScript owns behaviour that needs computation, state or the network.
- The rule of least power is a tie-breaker: use the least powerful tool that does the job.
- CSS is render blocking by default; scripts without
async,deferor module type block parsing. deferand module scripts run after parsing, in document order;asyncscripts run when ready, in no guaranteed order.- Keep layers decoupled through deliberate hooks, custom properties and cascade layers.
- Progressive enhancement is a baseline plus enhancements, decided per feature.
Practice exercises
Exercise 1: Starter (30 min). Take any page you know and write three columns: what HTML provides, what CSS provides, what only JavaScript provides. Find one feature that uses more power than it needs.
Exercise 2: Intermediate (2 hours). In a page of your own, put a classic script, a defer script and an async script in the head, each logging when it runs and when DOMContentLoaded fires. Reload several times and describe the order and what varies.
Exercise 3: Advanced (half day). Pick a component from a real application. Draw its hooks, its custom properties and its baseline. Then write a layer order for its stylesheet and explain, with the MDN rules, which rule wins in two conflicting cases.
Related reading
In this course:
- Frontend System Design: The Big Picture: where this layering sits in the whole discipline.
- The Critical Rendering Path: how the browser turns these three resources into pixels.
- How Browsers Work: parsing, styling and scripting in one engine.
- Rendering Pipeline: Layout, Paint and Compositing: what happens after style.
- Component-Based Architecture: the unit of separation in modern front ends.
- Content Security Policy: how inline scripts and styles interact with a security policy.
Official documentation
- W3C TAG: The Rule of Least Power: the principle behind "use the least powerful tool".
- MDN: progressive enhancement: the definition used here.
- MDN: the script element:
async,defer, modules and blocking. - web.dev: render-blocking CSS: which stylesheets block rendering.
- MDN: @layer: layer order, unlayered styles and
!important. - MDN: using custom elements: naming, definition and lifecycle.