Skip to content
jshacks.dev
Browser

Add a noscript fallback for critical features

Add a noscript element for features that need JavaScript, and a class on html that scripts swap, so the page degrades to something usable.

1 min read
Summarize in AI

If the script fails or is blocked, a page that depends on it should say so and offer another route. <noscript> and a class on the root element cover both cases.

fallback.htmlHTML
<html class="no-js">
<head>
  <script>document.documentElement.className = 'js';</script>
  <style>
    .no-js .needs-js { display: none; }
    .js .only-no-js { display: none; }
  </style>
</head>
<body>
  <noscript>
    <p>Search needs JavaScript. <a href="/sitemap">Browse the sitemap instead.</a></p>
  </noscript>
  <form class="needs-js" id="search">...</form>
</body>
</html>
search.jsJavaScript
console.log(document.documentElement.className);
Text
js

The inline script runs before anything paints and replaces no-js with js, so CSS hides the controls that do nothing without scripts. The <noscript> content is shown only when scripting is disabled. Both approaches are described in the noscript element.

This does not help when the script is blocked halfway, for example by a failed network request. Design forms to work as plain HTML first, such as a real action and method, and enhance them with JavaScript. A search box that submits to /search?q= works with no script at all.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.