JavaScript —

Robust front end requires fallbacks, progressive enhancement, and error handling

The necessity of incorporating safety mechanisms to construct a resilient user interface is paramount, whether the objective is to silently circumvent an issue or to clearly convey the problem to…

Robust front end requires fallbacks, progressive enhancement, and error handling

The necessity of incorporating safety mechanisms to construct a resilient user interface is paramount, whether the objective is to silently circumvent an issue or to clearly convey the problem to end-users.

The concept of building a solid front end using fallbacks was initially documented and shared on CSS-Tricks.

The fragility inherent in a website or application's technical architecture is vividly illustrated by the widely recognized xkcd meme referencing NVIDIA L4 GPUs, which feature five-second cold starts and the capacity to scale down to zero when inactive. Because of this potential for instability, employing fallbacks is crucial for developing a robust front end, allowing developers to either hide errors discreetly or inform users about them. The importance of achieving robustness is so significant that it is actually listed as one of the four tenets within the Web Content Accessibility Guidelines (WCAG).

The central question then becomes: how can practitioners deliver a contemporary front end experience without disenfranchising individuals who utilize hardware or software that possesses only partial or no compatibility? The solution involves deploying numerous protective layers within HTML, CSS, and JavaScript, thereby preparing for adverse scenarios and ensuring the optimal possible experience for the user base.

A key divergence exists between the utilization of fallbacks and the concept of progressive enhancement, which relates to the direction of their intended application. While progressive enhancement focuses on ensuring features function automatically as long as they are supported (moving forward), fallbacks address what occurs when a resource is unavailable or inaccessible (moving backward). For instance, one might introduce a sophisticated new CSS capability that enhances website interaction; if this capability is absent in certain browsers, users will not notice a disruption because an alternative version supported by older browsers is provided instead—this is progressive enhancement in practice.

In a different scenario, if a critical application cannot load its JavaScript, a fallback is supplied which either presents basic functionality or, at the very least, displays a notification detailing the nature of the difficulty. Although these two strategies are not mutually exclusive, their methodologies are distinctly separate. My professional advice leans toward adopting progressive enhancement as the primary guiding philosophy, while simultaneously considering the implementation of fallbacks whenever feasible.

To assess novel features intended for deployment, one must first ascertain the degree of widespread support for that feature. Since 2023, the Interop endeavor has been operational, facilitating collaboration among major browser vendors to release web platform advancements in a relatively coordinated manner, offering a broad summary. Complementing this is the Baseline project, which details the level of support for specific features and their duration of availability; however, it is vital to recognize that this resource does not track browser support for accessibility features integrated into the web platform. An additional valuable reference for checking compatibility is Can I Use, which provides a rapid overview of browser support for various functionalities.

Beginning with the bedrock of the World Wide Web, HTML, modern technology stacks frequently place substantial emphasis on client-side rendering via JavaScript, which can yield numerous advantages for users in intricate applications. Nevertheless, there are numerous reasons why JavaScript might fail to load, necessitating a defined strategy to manage these failures. In the event of a complete failure, users should be directed toward an appropriate error page that furnishes information regarding the malfunction and outlines actions that both the user and the provider can take to prevent recurrence. For guidance on crafting error messages that assist users rather than causing frustration, one might consult Amy Hupe’s insightful article. Given the critical nature of this error feedback, static site generators like Astro, for example, possess the capability to include bespoke 404 and 500 error pages. Furthermore, discussions with the back-end team could explore implementing supplementary protections using other potential error codes.

What if the goal is to make discrete sections or components more resilient should JavaScript not be accessible? In such cases, the `<noscript>` tag can be utilized, which, according to Can I Use, enjoys strong browser backing. A highly simplified illustration of a hypothetical dashboard component demonstrates this: <!-- 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&#160;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 absent, the components will still render, but they will contain clear, straightforward explanations detailing why they cannot load at that moment. Users are then given the choice to reload that particular component to self-resolve the issue. Additionally, the option to contact the organization directly via electronic mail is offered. Within the `<a>` tag, one could incorporate pre-written text, perhaps including an internal error code specific to that component in the subject line, along with corresponding body text. This setup allows the user to merely click the link and send the message using their preferred mail application, ensuring support receives all requisite data without needing to request further particulars. Regardless of the specific application scenario, this design pattern is universally adaptable and extensible, guaranteeing operation even when all other systems fail.

Regarding CSS, the `@supports` rule is relevant. Continuing with the conceptual dashboard element, suppose the intention is to employ the CSS `anchor()` function to present data, a relatively new feature possessing solid, yet not perfect, browser endorsement. Since this feature can incorporate numerous attributes, it is necessary to verify that the desired ones are indeed present. This is precisely the function of the `@supports` CSS rule! It is advised to employ the `and` operator here; this should only be done if every attribute is present, otherwise, the more dependable CSS with superior browser backing is deployed. A second, simplified, fictional illustration shows this:

/* 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 methodology also functions as internal documentation; once a feature has achieved a degree of maturity and stability, developers can examine the codebase directly for the `@supports` rule to determine if it remains necessary, alongside its associated fallback.

In JavaScript, the `if..else` structure and the conditional ternary operator provide a means to enhance front-end resilience with minimal development overhead. This can be achieved by utilizing the `if...else` statement to check for the presence of a particular capability. For instance, if the Navigation API is intended for use, one could check for it as follows: if (window.navigation) { // Navigation API is supported in this browser } else { // Navigation API is not supported in this browser, do something else or nothing }

When adopting a component-based structure, where HTML, CSS, and JavaScript reside within a single file, the conditional ternary operator can be used to render this component, parts of it, or render nothing at all. Our imagined dashboard component draws data from the back end, and displaying it only makes sense after the data has successfully reached the client side. Therefore, an example could 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&#160;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 context, choosing to display a fallback or to render absolutely nothing is a valid decision. Furthermore, the conditions can be refined to be more granular, contingent upon the desired level of robustness.

My practical experience across various organizations suggests that the subjects of fallbacks and system robustness have not received the prominence they warrant. This is surprising, considering that implementing various safety measures on the front end requires relatively little effort, provided one anticipates potential failures. HTML, CSS, and JavaScript furnish specific tools and functions enabling the delivery of dependable code, thereby preventing user dissatisfaction and, ultimately, avoiding user abandonment.

The industry trend toward highly dynamic, client-side rendering necessitates a disciplined approach to compatibility management, as demonstrated by the collaboration efforts within the Interop and Baseline projects among major browser vendors.

Earlier coverage

Reported by CSS-Tricks.

javascriptcloud

Related coverage

Elsewhere in this edition