· JavaScript
CSS-Tricks article details using fallbacks for a robust front end
For instance, in a fictional dashboard component, if JavaScript isn't accessible, we can still present the elements while clearly explaining the loading issue and providing users with options to…
For instance, in a fictional dashboard component, if JavaScript isn't accessible, we can still present the elements while clearly explaining the loading issue and providing users with options to refresh the specific part or reach out to support via email. This principle of building resilience is vital, as the importance of robustness is so significant that it is actually one of the four tenets of the Web Content Accessibility Guidelines (WCAG).
The concept of implementing fallbacks is crucial for constructing a resilient front end, whether the goal is to silently bypass an error or to effectively communicate the problem to the end-user. This necessity stems from the inherent fragility of a website or application's technical foundation, a concept vividly illustrated by the legendary meme from xkcd, which depicts NVIDIA L4 GPUs, five-second cold starts, and scaling to zero when idle.
The distinction between fallbacks and progressive enhancement hinges on their directional focus: progressive enhancement aims to automatically enable features whenever they are supported (moving forward), whereas fallbacks address what occurs when something is unavailable or inaccessible (moving backward). For example, one might deploy a sophisticated new CSS feature to enhance site interaction, but if some browsers lack support, users won't notice because a version compatible with older browsers is served instead—that's progressive enhancement in action! Conversely, if a critical application fails to load necessary JavaScript, a fallback is deployed, which either furnishes basic functionality or, at minimum, displays a message detailing the issue. While these two strategies are not mutually exclusive, their operational methods diverge significantly. Personally, I advise adopting progressive enhancement as the guiding philosophy while incorporating fallbacks whenever feasible.
To properly assess new features destined for production, one must first ascertain the degree of feature support. Since 2023, the Interop project has been active, bringing together major browser developers to release web platform features in a relatively synchronized manner, providing a broad overview. Complementing this is the Baseline project, which details support levels for particular features and their availability duration; nevertheless, it is crucial to understand that this resource does not track browser support for accessibility features embedded within the web platform. For a rapid check on compatibility across various features, Can I Use stands out as another valuable resource.
Focusing on the bedrock of the World Wide Web, HTML, we face the reality that modern tech stacks often rely heavily on client-side rendered JavaScript, which brings many advantages to complex applications. However, numerous reasons exist for JavaScript to fail loading, necessitating a strategy to manage these failures. In the event of a complete failure, users should be directed toward an appropriate error page that informs them about the malfunction and outlines steps for both them and us to prevent recurrence. For guidance on drafting helpful error messages rather than frustrating users, Amy Hupe’s insightful article is worth consulting. Because this type of error feedback is so vital, static site generators like Astro offer the capability to incorporate custom 404 and 500 error pages. Furthermore, one might consult with the back-end team to implement additional protective measures via other error codes.
But what if we aim for greater resilience within specific components or sections when JavaScript is absent? Here, the `<noscript>` tag becomes useful, and Can I Use indicates it possesses excellent browser support. Consider this simplified illustration of a hypothetical dashboard component:
`<!-- Shown if no JavaScript was detected -->` `<noscript> <section aria-labelledby="user-statistics-heading"> <h2 id="user-statistics-heading">User statistics:</h2> <p>Unfortunately, the user statistics could not be loaded because JavaScript is not available. Please click the “Refresh” button to try again. If the problem persists, click “Report problem” to contact our support team directly.</p> <button type="button">Refresh</button> <a href="mailto:[email protected]">Report problem</a> </section> </noscript>` `<!-- Shown if JavaScript was detected -->` `<section aria-labelledby="user-statistics-heading"> <h2 id="user-statistics-heading">User statistics:</h2> <!-- Actual code --> </section>`
When JavaScript is missing, the components will still appear, but they will convey in simple, clear language that they cannot load at that moment and why. Users are then given the choice to reload that component to attempt a self-resolution, or they can opt to email support directly if the issue continues. In this latter case, one could embed pre-written text into the `<a>` tag, perhaps including an internal error code specific to that component in the subject line and a corresponding body, allowing the user to send the email immediately through their preferred mail client. This setup ensures support receives all requisite information without needing to request further details. Regardless of the specific scenario, this pattern is universally adaptable and extends to guarantee functionality even when other elements fail.
Moving to CSS, the `@supports` rule offers a solution. Continuing with our example dashboard component, suppose we wish to employ the CSS `anchor()` function to display data, a relatively new feature with solid, though not perfect, browser backing. Since this feature can involve multiple attributes, we must verify that the desired ones are actually present—and this is precisely where the `@supports` CSS rule intervenes! It is advised to utilize the `and` operator here, meaning the code should only execute if every specified attribute is supported; otherwise, the more stable CSS with broader browser acceptance is used. Here is another simplified, fictional illustration:
`/* Fallback for unsupported browsers */ section[aria-labelledby="user-statistics-heading"] { position: relative; }` `/* Available in supported browsers */ @supports (top: anchor(bottom)) and (position-anchor: auto) { section[aria-labelledby="user-statistics-heading"] { position: absolute; top: anchor(#target bottom); position-anchor: #target; } }`
This method also functions as a form of code documentation; once a feature has matured and become more established, developers can examine the codebase for the `@supports` rule to determine if it remains necessary, along with its corresponding fallback.
JavaScript provides a straightforward means to make our front end even more resilient with minimal effort. The `if...else` statement allows us to check for the presence of a specific capability. For instance, if we intend to use the relatively new Navigation API, the check could look like this: `if (window.navigation) { // Navigation API is supported in this browser } else { // Navigation API is not supported in this browser, do something else or nothing }`. If we are utilizing a component-based architecture where HTML, CSS, and JavaScript reside in one file, the conditional ternary operator can be employed to render the component, parts of it, or nothing at all. Our hypothetical dashboard component requires backend data, making it only sensible to render once that data has successfully arrived on the front end. Therefore, an approach might look like this:
`// Option 1: Show component because JavaScript is not available:` `{ userdata ? <section aria-labelledby="user-statistics-heading"> <h2 id="user-statistics-heading">User statistics:</h2> <!-- Actual code --> </section> : <noscript> <section aria-labelledby="user-statistics-heading"> <h2 id="user-statistics-heading">User statistics:</h2> <p>Unfortunately, the user statistics could not be loaded because JavaScript is not available. Please click the “Refresh” button to try again. If the problem persists, click “Report problem” to contact our support team directly.</p> <button type="button">Refresh</button> <a href="mailto:[email protected]">Report problem</a> </section> </noscript> }` `// Option 2: Don't show anything at all if no user data is available:` `{ userdata ? <section aria-labelledby="user-statistics-heading"> <h2 id="user-statistics-heading">User statistics:</h2> <!-- Actual code --> </section> : null }`
Depending on the specific requirement, it might be appropriate to display a fallback or, conversely, display nothing at all. Furthermore, conditions can be defined with greater specificity based on the desired level of robustness.
Reflecting on my professional experiences across various organizations, I find that the subjects of robustness and fallbacks have not received the prominence they deserve. This is surprising, given that we have learned it requires relatively little effort to implement various safety nets on the front end, provided one anticipates potential failures. HTML, CSS, and JavaScript furnish us with specific tools and functions to deliver sturdy code, thereby preventing user dissatisfaction and, at worst, avoiding customer attrition.





