EthicsComputerCourses
Join training +91 90532 10052

Progressive Enhancement

HTML · Lesson 90 of 234 Advanced 10 min read Updated

By the end of this lesson you will be able to build a page whose main task works with HTML alone, add CSS and JavaScript as layers on top, turn a plain search form into live search without breaking it, and test what happens when scripts fail.

What you should know first: HTML Integration with JavaScript and HTML with Modern JavaScript for fetch and modules, HTML Forms Introduction for action and method, and Cross-Browser Compatibility for feature detection.

The three layers

Progressive enhancement means you build the core experience with the simplest, most reliable technology first, and then add improvements for browsers that can use them. Each layer is optional for the one below it.

LayerIts jobIf it fails to load
HTMLContent, links, forms: the core taskNothing works (so keep it solid)
CSSLayout, colour, readabilityThe page looks plain but still works
JavaScriptSpeed and convenience: live results, no reloadsThe page reloads more, but still works

Think of booking a train ticket. The reservation counter at the station is the HTML layer: slow, but it always works. The app is the JavaScript layer: faster and nicer. When the app is down, you can still walk to the counter. A site built with progressive enhancement always keeps the counter open.

Why it matters on Indian mobile networks

Every visitor is a "no JavaScript" visitor until your script has downloaded, parsed and run. On a fast laptop that takes a moment. Elsewhere it can take much longer, or never finish:

  • A student on a local train loses signal between stations, and the script download stalls halfway.
  • A budget Android phone with a slow processor takes seconds to parse a large bundle.
  • A college or office proxy, a browser extension or a data-saver mode blocks a third-party script.
  • One uncaught error in your bundle stops everything after it.
  • The CDN that serves your library is slow or unreachable from one region.

In each case, a page that needs JavaScript for basic tasks shows a blank screen or a dead button. A page built in layers still lets Isha in Lucknow search, read and submit, just with full page loads.

Layer 1: HTML that works alone

The HTML layer uses the features browsers have supported for decades:

  • Links are real <a href> elements that point to real URLs. Search engines and "open in new tab" depend on them too; see Crawlable Links.
  • Forms have an action and a method. Use method="get" for searches and filters, so the query lands in the URL and can be bookmarked or shared on WhatsApp. Use method="post" for actions that change data, such as placing an order.
  • Buttons are <button> elements inside forms, so they submit even when no script is listening.
HTML
<!-- Breaks without JavaScript -->
<div class="link" onclick="location.href='/fees'">Fee structure</div>
<a href="#" onclick="loadMore()">Load more</a>

<!-- Works without JavaScript; a script can still enhance it -->
<a href="/fees">Fee structure</a>
<a href="/notices?page=2" id="more">Load more</a>

The second "Load more" link is a normal link to page 2. A script can later catch the click, fetch page 2 and add the items in place. If the script never arrives, the link simply opens page 2. Tabs work the same way: start with in-page links such as <a href="#timings"> pointing to sections that are all visible, then let a script turn them into tabs.

Layer 2: CSS that improves, never hides

Write HTML in a sensible reading order, so the page makes sense even unstyled. Then add CSS. Two rules keep this layer safe:

  • Never hide content with CSS that only JavaScript can reveal. If the script fails, the content is lost.
  • Wrap newer layout features in @supports, so older browsers keep a simpler layout. Graceful Degradation shows this in detail.

Layer 3: JavaScript that enhances

The script layer starts by asking, "Can this browser do what I need?" This is feature detection. If the answer is no, the script quietly does nothing, and the HTML layer keeps working.

JavaScript
if ("fetch" in window && "AbortController" in window) {
  enhanceSearch();          // live results
}                           // otherwise: the normal form submit still works

Two more habits help. A type="module" script is ignored by very old browsers, so it acts as a free first filter. And controls that only make sense with JavaScript, such as a "Clear filters" button that works in place, should start hidden in the HTML or be created by the script. Then visitors without scripts never see a button that does nothing.

Farhan wants a search box for a notice board. We use the test server at jsonplaceholder.typicode.com, which supports a q parameter for text search in its posts.

Step 1: the HTML layer alone

This version has no script at all. Type "dolorem" and press Search.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Notice search: HTML only</title>
</head>
<body>
  <h1>Notice board search</h1>
  <search>
    <form action="https://jsonplaceholder.typicode.com/posts" method="get">
      <label for="q">Search notices</label>
      <input id="q" name="q" type="search" required>
      <input type="hidden" name="_limit" value="5">
      <button>Search</button>
    </form>
  </search>
</body>
</html>

The frame loads https://jsonplaceholder.typicode.com/posts?q=dolorem&_limit=5 and shows the matching posts. A real site's server would send back an HTML results page; this test server sends raw JSON, which is enough to prove the request works with no JavaScript. Notice that required blocks an empty search, also without a script.

Step 2: add the JavaScript layer

Now we keep the exact same form and add a module script:

  1. Check for fetch and AbortController. If they are missing, stop.
  2. Reveal a hint that only makes sense with JavaScript.
  3. On each input event, wait 300 milliseconds after the last key press. This wait is called a debounce and saves data on slow networks.
  4. Build the URL from the form itself with FormData, so both paths send the same query.
  5. Cancel the previous request, fetch, and render results with textContent.
  6. Catch submit too, so pressing Enter shows results without a reload.
HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Notice search: enhanced</title>
</head>
<body>
  <h1>Notice board search</h1>
  <search>
    <form id="search" action="https://jsonplaceholder.typicode.com/posts" method="get">
      <label for="q">Search notices</label>
      <input id="q" name="q" type="search" required>
      <input type="hidden" name="_limit" value="5">
      <button>Search</button>
      <p id="hint" hidden>Results update as you type.</p>
    </form>
  </search>
  <p id="status" role="status"></p>
  <ol id="results"></ol>

  <script type="module">
    const form = document.querySelector("#search");
    const status = document.querySelector("#status");
    const results = document.querySelector("#results");

    if ("fetch" in window && "AbortController" in window) {
      document.querySelector("#hint").hidden = false;
      let controller;
      let timer;

      async function search() {
        const query = form.q.value.trim();
        if (query.length < 2) {
          results.replaceChildren();
          status.textContent = "";
          return;
        }
        controller?.abort();
        controller = new AbortController();
        const url = `${form.action}?${new URLSearchParams(new FormData(form))}`;
        status.textContent = "Searching...";
        try {
          const response = await fetch(url, { signal: controller.signal });
          if (!response.ok) throw new Error(response.status);
          const posts = await response.json();
          results.replaceChildren(...posts.map((post) => {
            const li = document.createElement("li");
            li.textContent = post.title;
            return li;
          }));
          status.textContent = `${posts.length} results for "${query}"`;
        } catch (err) {
          if (err.name === "AbortError") return;     // a newer search replaced this one
          status.textContent = "Live search failed. Press Search to try the normal way.";
        }
      }

      form.addEventListener("input", () => {
        clearTimeout(timer);
        timer = setTimeout(search, 300);
      });
      form.addEventListener("submit", (event) => {
        event.preventDefault();
        clearTimeout(timer);
        search();
      });
    }
  </script>
</body>
</html>

Type "dolorem" slowly. After you stop typing, the status reads 5 results for "dolorem" and five titles appear, starting with "eum et est occaecati" (the server also searches the body text). Only one request goes out per pause, and older ones are cancelled. If the script fails to load, the visitor gets Step 1's behaviour: the same form, the same URL, a full page load.

Testing with JavaScript turned off

Make this part of every review, not a one-time check.

  1. Step 1: open DevTools in Chrome or Edge, press Ctrl+Shift+P, type "Disable JavaScript" and press Enter. Reload. Complete the main task: search, read, submit. You should see full page loads, but no dead ends.
  2. Step 2: turn JavaScript back on. In the Network panel, choose a slow preset such as "3G" from the throttling menu and reload. Try to use the page while scripts are still loading.
  3. Step 3: in the Network panel, right-click your main script and choose "Block request URL". Reload. This copies a failed CDN or a blocked file.
  4. Step 4: in Firefox, use View, Page Style, No Style to check the HTML reading order without CSS.
  5. Step 5: test on a real low-cost Android phone on mobile data, outside office Wi-Fi.

The JavaScript setting only lasts while DevTools is open, so close DevTools when you finish.

Common mistakes

  • <a href="#"> or <div onclick> for navigation. Use real links with real URLs.
  • Forms with no action. Without the script, submit just reloads the same page.
  • Content hidden until a script reveals it. If the script fails, the content is gone.
  • Showing JS-only buttons in the HTML. Hide them by default or create them in the script.
  • Building the live URL by hand. Use FormData so both paths always send the same query.
  • Testing only on fast office Wi-Fi. Throttle, block scripts and use a real phone.

Interview questions

1. What is progressive enhancement?

It is a strategy where the core content and tasks are built with plain HTML that works everywhere, and CSS and JavaScript are added as layers that improve the experience where supported. If a layer fails, the page still works at the level below.

2. Why should a search form use method="get"?

A GET form puts the query in the URL, so results can be bookmarked, shared, cached and crawled, and the back button behaves well. POST is for requests that change data on the server.

3. How do you enhance a form without breaking it?

Keep a working action and method, then listen to submit or input in a script, call preventDefault() and fetch the same URL built from FormData. If the script fails, the browser submits the form normally.

4. What is feature detection and why is it better than checking the browser name?

It tests whether a feature exists, such as "fetch" in window, before using it. Browser names and versions change and are often wrong in the user agent string, while a feature test gives the true answer for that browser.

5. How would you test a page for progressive enhancement?

Disable JavaScript in DevTools and complete the main tasks, throttle the network to a slow preset, block the main script URL, view the page without CSS and test on a real low-end phone on mobile data.

Key points

  • Build in layers: HTML for the core task, CSS for looks, JavaScript for convenience.
  • Every visitor is a no-JavaScript visitor until your script runs; slow networks and phones make that window long.
  • Use real links and forms with action and method; use GET for searches.
  • Enhance with feature detection, intercept submit or input, and reuse the form's own URL and data.
  • Hide or create JS-only controls in the script, and never hide content that only a script can reveal.
  • Test with JavaScript disabled, throttled networks and blocked scripts.

Exercise

Build a "Frequently asked questions" page for a Jaipur coaching centre with six questions, each an <h2> followed by a <p>. Without JavaScript, every question and answer must be visible. Add a module script that, only if "replaceChildren" in Element.prototype, creates a labelled search box above the list and hides the questions whose heading or answer does not contain the typed text. Show a count such as "2 of 6 questions" in a status element that the script also creates.

Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>FAQ</title>
</head>
<body>
  <h1>Coaching centre FAQ</h1>
  <div id="faq">
    <section><h2>What are the batch timings?</h2><p>Morning 7 to 9 and evening 5 to 7.</p></section>
    <section><h2>Is there a demo class?</h2><p>Yes, the first class is free.</p></section>
    <section><h2>Can I pay fees by UPI?</h2><p>Yes, UPI and cash are accepted.</p></section>
    <section><h2>Do you give study material?</h2><p>Printed notes are given every week.</p></section>
    <section><h2>Are there weekend batches?</h2><p>Yes, on Saturday and Sunday mornings.</p></section>
    <section><h2>Where is the centre?</h2><p>Near the Malviya Nagar metro station.</p></section>
  </div>
  <script type="module">
    if ("replaceChildren" in Element.prototype) {
      const faq = document.querySelector("#faq");
      const sections = [...faq.children];
      const label = document.createElement("label");
      label.textContent = "Search questions ";
      const input = document.createElement("input");
      input.type = "search";
      label.append(input);
      const status = document.createElement("p");
      status.setAttribute("role", "status");
      faq.before(label, status);

      input.addEventListener("input", () => {
        const q = input.value.trim().toLowerCase();
        let shown = 0;
        for (const s of sections) {
          const match = s.textContent.toLowerCase().includes(q);
          s.hidden = !match;
          if (match) shown++;
        }
        status.textContent = `${shown} of ${sections.length} questions`;
      });
    }
  </script>
</body>
</html>

All six answers are plain HTML, so they show with JavaScript off. The search box and status are created by the script, so visitors without scripts never see a control that does nothing.

Quick Quiz

1. Which link still works when JavaScript fails to load?

2. Why use method="get" for a search form?

3. A "Clear filters" button only works with JavaScript. Where should it come from?

4. In Chrome DevTools, how do you quickly turn JavaScript off for a test?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call