| 1 |
--- |
| 2 |
title: "You Can't Build Interactive Web Apps Except as Single Page Applications... And Other Myths" |
| 3 |
description: "Tony Alaribe challenges common myths about multi-page applications (MPAs) and explores how modern browser technologies can enable fast, interactive, and offline-capable web applications without relying on single-page application (SPA) frameworks. Alaribe discusses advancements in service workers, caching, and cross-document transitions, offering insights into building efficient MPAs. By debunking myths like slow page transitions and the necessity of JavaScript-heavy frameworks, Alaribe highlights how developers can leverage HTML, CSS, and minimal JavaScript to create robust, user-friendly web apps in 2024." |
| 4 |
created: 2024-09-20 |
| 5 |
modified: 2024-09-20 |
| 6 |
authors: ["Tony Alaribe"] |
| 7 |
tags: ["case-studies"] |
| 8 |
--- |
| 9 |
|
| 10 |
import { Image } from 'astro:assets'; |
| 11 |
import serviceWorkerChart from '../../assets/img/you-cant/service-worker-chart.png'; |
| 12 |
import workboxCfg from '../../assets/img/you-cant/workbox-cfg.png'; |
| 13 |
import serviceWorker from '../../assets/img/you-cant/service-worker.png'; |
| 14 |
import speculationRules from '../../assets/img/you-cant/speculation-rules.png'; |
| 15 |
import workboxOfflineCfg from '../../assets/img/you-cant/workbox-offline-cfg.png'; |
| 16 |
import crossDocTransitionsCss from '../../assets/img/you-cant/cross-doc-transitions-css.png'; |
| 17 |
|
| 18 |
### **An Ode to Browser Advancements.** |
| 19 |
|
| 20 |
I often encounter discussions on Reddit and YCombinator where newer developers seek tech stack advice. Inevitably, |
| 21 |
someone claims it's impossible to build a high-quality application without using a single-page application (SPA) |
| 22 |
framework like React or AngularJS. This strikes me as odd because, even before the SPA revolution, many popular |
| 23 |
multi-page web applications offered excellent user experiences. |
| 24 |
|
| 25 |
Two years ago, I set out to build an [observability platform](https://apitoolkit.io) and chose to experiment with a |
| 26 |
multi-page application (MPA) approach using HTMX. I wondered: Would a server-rendered MPA be inadequate for a data-heavy |
| 27 |
application, considering that most observability platforms are built on ReactJS? |
| 28 |
|
| 29 |
What I discovered is that you can create outstanding server-rendered applications if you pay attention to certain |
| 30 |
details. |
| 31 |
|
| 32 |
**Here are some common MPA myths and what I've learned about them.** |
| 33 |
|
| 34 |
## Myth 1: MPA Page Transitions are slow because JavaScript and CSS are downloaded on every page navigation |
| 35 |
|
| 36 |
The perception that MPA page transitions are slow is widespread—and not entirely unfounded—since this is the default |
| 37 |
behavior of browsers. However, browsers have made significant improvements over the past decade to mitigate this issue. |
| 38 |
|
| 39 |
To illustrate, in the video below, a full page reload with the cache disabled takes 2.90 seconds until the |
| 40 |
DOMContentLoaded event fires. I recorded this at a café with poor Wi-Fi, but let's use this as a reference point. Keep |
| 41 |
that number in mind. |
| 42 |
|
| 43 |
<video controls> |
| 44 |
<source src="/img/you-cant/log-exp-cache.mp4"/> |
| 45 |
</video> |
| 46 |
|
| 47 |
It is common to reduce load times in MPAs using libraries such as **PJAX, Turbolinks, and even HTMX Boost**. These |
| 48 |
libraries hijack the page reload using Javascript and swap out only the HTML body element between transitions. That way, |
| 49 |
most of the page's head section assets don't need to be reloaded or re-downloaded. |
| 50 |
|
| 51 |
But there’s a lesser known way of reducing how much assets are re-downloaded or evaluated during page transitions. |
| 52 |
|
| 53 |
### Client-side Caching via Service workers |
| 54 |
|
| 55 |
Frontend developers who have built Progressive Web Applications (PWA) with SPA frameworks might know about service |
| 56 |
workers. |
| 57 |
|
| 58 |
For those of us who are not frontend or PWA developers, service workers are a built-in feature of browsers. They let you |
| 59 |
write Javascript code that sits between your users and the network, intercepting requests and deciding how the browser |
| 60 |
handles them. |
| 61 |
|
| 62 |
<Image src={serviceWorkerChart} alt="Service worker chart"/> |
| 63 |
|
| 64 |
Due to its association with the PWA trend, service workers are only ordinary among SPA developers, and developers need |
| 65 |
to realize that this technology can also be used for regular Multi-Page Applications. |
| 66 |
|
| 67 |
<video controls> |
| 68 |
<source src="/img/you-cant/log-exp-with-cache.mp4"/> |
| 69 |
</video> |
| 70 |
|
| 71 |
In the video demonstration, we enable a service worker to cache and refresh the current page. You'll notice that there's |
| 72 |
no flicker when clicking the link to reload the page, resulting in a smoother user experience. |
| 73 |
|
| 74 |
Moreover, instead of transmitting over 2 MB of static assets as before, the browser now only fetches 84 KB of HTML |
| 75 |
content—the actual page data. This optimization reduces the `DOMContentLoaded` event time from 2.9 seconds to under 500 |
| 76 |
milliseconds. Impressively, this improvement is achieved **without** using HTMX Boost, PJAX, or Turbolinks. |
| 77 |
|
| 78 |
### How to Implement Service workers in Your Multi-Page Application |
| 79 |
|
| 80 |
You might be wondering how to replicate these performance gains in your own MPA. Here's a simple guide: |
| 81 |
|
| 82 |
1. **Create a `sw.js` File**: This is your service worker script that will manage caching and network requests. |
| 83 |
2. **List Files to Cache**: Within the service worker, specify all the assets (HTML, CSS, JavaScript, images) that |
| 84 |
should be cached. |
| 85 |
3. **Define Caching Strategies**: Indicate how each type of asset should be cached—for example, whether they should be |
| 86 |
cached permanently or refreshed periodically. |
| 87 |
|
| 88 |
By implementing a service worker, you effectively tell the browser how to handle network requests and caching, leading |
| 89 |
to faster load times and a more seamless user experience. |
| 90 |
|
| 91 |
### Use Workbox to generate service workers |
| 92 |
|
| 93 |
While it's possible to write service workers by hand—and there are excellent resources |
| 94 |
like [this MDN article](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) to |
| 95 |
help you—I prefer using Google's [Workbox](https://developer.chrome.com/docs/workbox) library to automate the process. |
| 96 |
|
| 97 |
### Steps to Use Workbox: |
| 98 |
|
| 99 |
1. **Install Workbox**: Install Workbox via npm or your preferred package manager: |
| 100 |
|
| 101 |
```bash |
| 102 |
npm install workbox-cli --global |
| 103 |
``` |
| 104 |
|
| 105 |
2. Generate a Workbox Configuration file: Run the following command to create a configuration file: |
| 106 |
|
| 107 |
```bash |
| 108 |
workbox wizard |
| 109 |
``` |
| 110 |
|
| 111 |
3. **Configure Asset Handling**: In the generated `workbox-config.js` file, define how different assets should be |
| 112 |
cached. Use the `urlPattern` property—a regular expression—to match specific HTTP requests. For each matching |
| 113 |
request, specify a caching strategy, such as `CacheFirst` or `NetworkFirst`. |
| 114 |
|
| 115 |
<Image src={workboxCfg} alt="Workbox configuration example" /> |
| 116 |
|
| 117 |
|
| 118 |
1. **Build the Service Worker**: Run the Workbox build command to generate the `sw.js` file based on your configuration: |
| 119 |
|
| 120 |
```bash |
| 121 |
workbox generateSW workbox-config.js |
| 122 |
``` |
| 123 |
|
| 124 |
2. **Register the Service Worker in Your Application**: Add the following script to your HTML pages to register the |
| 125 |
service worker: |
| 126 |
|
| 127 |
```html |
| 128 |
<script> |
| 129 |
if ('serviceWorker' in navigator) { |
| 130 |
window.addEventListener('load', function() { |
| 131 |
navigator.serviceWorker.register('/sw.js').then(function(registration) { |
| 132 |
console.log('ServiceWorker registration successful with scope: ', registration.scope); |
| 133 |
}, function(err) { |
| 134 |
console.log('ServiceWorker registration failed: ', err); |
| 135 |
}); |
| 136 |
}); |
| 137 |
} |
| 138 |
</script> |
| 139 |
``` |
| 140 |
|
| 141 |
By following these steps, you instruct the browser to serve cached assets whenever possible, drastically reducing load |
| 142 |
times and improving the overall performance of your multi-page application. |
| 143 |
|
| 144 |
<Image src={serviceWorker} alt="Registered service worker in Chrome browser console" /> |
| 145 |
|
| 146 |
Image showing the registered service worker from the Chrome browser console. |
| 147 |
|
| 148 |
### [ |
| 149 |
|
| 150 |
`Speculation Rules API`](https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API): Prerender pages for |
| 151 |
instant page navigation. |
| 152 |
|
| 153 |
If you have used **htmx-preload** or **instantpage.js,** you're familiar with prerendering and the problem |
| 154 |
the [“Speculation Rules API”](https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API) aims to solve. The |
| 155 |
Speculation Rules API is designed to improve performance for future navigations. It has an expressive syntax for |
| 156 |
specifying which links should be prefetched or prerendered on the current page. |
| 157 |
|
| 158 |
<Image src={speculationRules} alt="Speculation rules configuration example" /> |
| 159 |
|
| 160 |
Speculation rules configuration example |
| 161 |
|
| 162 |
The script above is an example of how speculation rules are configured. It is a Javascript object, and without going |
| 163 |
into detail, you can see that it uses keywords such as “where,” “and,” “not,” etc. to describe what elements should |
| 164 |
either be prefetched or prerendered. |
| 165 |
|
| 166 |
<video controls> |
| 167 |
<source src="/img/you-cant/prerender-vid.mp4"/> |
| 168 |
</video> |
| 169 |
|
| 170 |
[Example impact of prerendering (Chrome Team)](https://developer.chrome.com/docs/web-platform/prerender-pages) |
| 171 |
|
| 172 |
## Myth 2: MPAs can't operate offline and save updates to retry when there's network |
| 173 |
|
| 174 |
From the last sections, you know that service workers can cache everything and make our apps operate entirely offline. |
| 175 |
But what if we want to save offline POST requests and retry them when there is internet? |
| 176 |
|
| 177 |
<Image src={workboxOfflineCfg} alt="Workbox offline configuration" /> |
| 178 |
|
| 179 |
The configuration javascript file above shows how to configure Workbox to support two common offline scenarios. Here, |
| 180 |
you see background Sync, where we ask the service worker to cache any failed requests due to the internet and retry it |
| 181 |
for up to 24 hours. |
| 182 |
|
| 183 |
Below, we define an offline catch Handler, triggered when a request is made offline. We can return a template partial |
| 184 |
with HTML or a JSON response or dynamically build a response based on the request input. The sky is the limit here. |
| 185 |
|
| 186 |
## Myth 3: MPAs always flash white during page Transitions |
| 187 |
|
| 188 |
In the service worker videos, we already saw that this will not happen if we configure caching and prerendering. |
| 189 |
However, this myth was not generally true until 2019. Since 2019, most browsers withhold painting the next screen until |
| 190 |
all the required assets for the next page are available or a timeout is reached, resulting in no flash of white while |
| 191 |
transitioning between both pages. This only works when navigating within the same origin/domain. |
| 192 |
|
| 193 |
<video controls> |
| 194 |
<source src="/img/you-cant/paint-holding.mp4"/> |
| 195 |
</video> |
| 196 |
|
| 197 |
[Paint holding documentation on chrome.com](https://developer.chrome.com/blog/paint-holding). |
| 198 |
|
| 199 |
## Myth 4: Fancy Cross-document page transitions are not possible with MPAs. |
| 200 |
|
| 201 |
The advent of single-page application frameworks made custom transitions between pages more popular. The allure of |
| 202 |
different navigation styles comes from completely taking control of page navigation from the browsers. In practice, such |
| 203 |
transitions have mostly been popular within the demos at web dev conference talks. |
| 204 |
|
| 205 |
<video controls> |
| 206 |
<source src="/img/you-cant/page-transitions.mp4"/> |
| 207 |
</video> |
| 208 |
|
| 209 |
|
| 210 |
[Cross Document Transitions documentation on chrome.com](https://developer.chrome.com/docs/web-platform/view-transitions). |
| 211 |
|
| 212 |
This remains a common argument for single-page applications, especially on Reddit and Hacker News comment sections. |
| 213 |
However, browsers have been working towards solving this problem natively for the last couple of years. Chrome 126 |
| 214 |
rolled out cross-document view transitions. This means we can build our MPAs to include those fancy animations and |
| 215 |
transitions between pages using CSS only or CSS and Javascript. |
| 216 |
|
| 217 |
My favorite bit is that we might be able to create lovely cross-document transitions with CSS only: |
| 218 |
|
| 219 |
<Image src={crossDocTransitionsCss} alt="Cross-document transitions CSS example" /> |
| 220 |
|
| 221 |
You can quickly learn more on |
| 222 |
the [Google Chrome announcement page](https://developer.chrome.com/docs/web-platform/view-transitions) |
| 223 |
|
| 224 |
This link hosts a [multi-page application demo](https://view-transitions.netlify.app/stack-navigator/mpa-prerender/), |
| 225 |
where you can play around with a rudimentary server-rendered application using the cross-document view transitions API |
| 226 |
to simulate a stack-based animation. |
| 227 |
|
| 228 |
## Myth 5: With htmx or MPAs, every user action must happen on the server. |
| 229 |
|
| 230 |
I've heard this a lot when HTMX is discussed. So, there might be some confusion caused by the HTMX positioning. But you |
| 231 |
don't have to do everything server-side. Many HTMX and regular MPA users continue to use Javascript, Alpine, or |
| 232 |
Hyperscript where appropriate. |
| 233 |
|
| 234 |
In situations where robust interactivity is helpful, you can lean into the component islands architecture using |
| 235 |
WebComponents or any javascript framework (React, Angular, etc.) of your choice. That way, instead of your entire |
| 236 |
application being an SPA, you can leverage those frameworks specifically for the bits of your application that need that |
| 237 |
interactivity. |
| 238 |
|
| 239 |
The example above shows a very interactive search component in the [APItoolkit](https://apitoolkit.io). It's a web |
| 240 |
component implemented with lit-element, a zero-compile-step library for writing web components. So, the entire web |
| 241 |
component event fits in a Javascript file. |
| 242 |
|
| 243 |
<video controls> |
| 244 |
<source src="/img/you-cant/webcomponents-filter-element2.mp4"/> |
| 245 |
</video> |
| 246 |
|
| 247 |
## Myth 6: Operating directly on the DOM is slow. Therefore, it would be best to use React/Virtual DOM. |
| 248 |
|
| 249 |
The speed of direct DOM operations was a major motivation for building ReactJS on and popularizing the virtual DOM |
| 250 |
technology. While virtual DOM operations can be faster than direct DOM operations, this is only true for applications |
| 251 |
that perform many complex operations and refresh in milliseconds, where that performance might be noticeable. But most |
| 252 |
of us are not building such software. |
| 253 |
|
| 254 |
The Svelte team wrote an excellent article |
| 255 |
titled [“Virtual DOM is pure Overhead.”](https://svelte.dev/blog/virtual-dom-is-pure-overhead) I recommend reading it, |
| 256 |
as it better explains why Virtual DOM doesn't matter for most applications. |
| 257 |
|
| 258 |
## Myth 7: You still need to write JavaScript for every minor interactivity. |
| 259 |
|
| 260 |
With the advancements in browser tech, you can avoid writing a lot of client-side Javascript in the first place. For |
| 261 |
example, a standard action on the web is to show and hide things based on a button click or toggle. These days, you can |
| 262 |
show and hide elements with only CSS and HTML, for example, by using an HTML input checkbox to track state. We can style |
| 263 |
an HTML label as a button and give it a `for="checkboxID`" attribute, so clicking the label toggles the checkbox. |
| 264 |
|
| 265 |
```javascript |
| 266 |
<input id="published" class="hidden peer" type="checkbox"/> |
| 267 |
<label for="published" class="btn">toggle content</label> |
| 268 |
|
| 269 |
<div class="hidden peer-checked:block"> |
| 270 |
Content to be toggled when label/btn is clicked |
| 271 |
</div> |
| 272 |
``` |
| 273 |
|
| 274 |
We can combine such a checkbox with HTMX intersect to fetch content from an endpoint when the button is clicked. |
| 275 |
|
| 276 |
```html |
| 277 |
<input id="published" class="peer" type="checkbox" name="status"/> |
| 278 |
<div |
| 279 |
class="hidden peer-checked:block" |
| 280 |
hx-trigger="intersect once" |
| 281 |
hx-get="/log-item" |
| 282 |
>Shell/Loading text etc |
| 283 |
</div> |
| 284 |
``` |
| 285 |
|
| 286 |
All the classes above are vanilla [Tailwind CSS](https://tailwindcss.com/) classes, but you can also write the CSS by |
| 287 |
hand. Below is a video of that code being used to hide or reveal log items in the log explorer. |
| 288 |
|
| 289 |
<video controls> |
| 290 |
<source src="/img/you-cant/expanding-log-item.mp4"/> |
| 291 |
</video> |
| 292 |
|
| 293 |
## Final Myth: Without a |
| 294 |
|
| 295 |
*“Proper”* frontend framework, your Client-side Javascript will |
| 296 |
be [Spaghetti and Unmaintainable](https://www.reddit.com/r/webdev/comments/bkk0gl/avoiding_the_vanillajs_spaghetticode/). |
| 297 |
|
| 298 |
This may or may not be true. |
| 299 |
|
| 300 |
### Who cares? I love Spaghetti. |
| 301 |
|
| 302 |
I like to argue that some of the most productive days of the web were the PHP and JQuery spaghetti days. A lot of |
| 303 |
software was built at that time, including many of the popular internet brands we know today. Most of them were built as |
| 304 |
so-called spaghetti codes, which helped them ship their products early and survive long enough to refactor and not be |
| 305 |
spaghetti. |
| 306 |
|
| 307 |
## Conclusion |
| 308 |
|
| 309 |
The entire point of this talk is to show you that a lot is possible with browsers in 2024. While we were not looking, |
| 310 |
browsers have closed the gap and borrowed the best ideas from the single-page application revolution. For example, |
| 311 |
WebComponents exist thanks to the lessons we learned from single-page applications. |
| 312 |
|
| 313 |
So now, we can build very interactive, even offline web applications using mostly browser tools—HTML, CSS, maybe some |
| 314 |
Javascript—and still not sacrifice much in terms of user experience. |
| 315 |
|
| 316 |
<h3>The browser has come a long way. Give it a chance!</h3> |