A place to cache linked articles (think custom and personal wayback machine)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.html 20KB

4 yıl önce
4 yıl önce
4 yıl önce
4 yıl önce
4 yıl önce
4 yıl önce
4 yıl önce
4 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. <!doctype html><!-- This is a valid HTML5 document. -->
  2. <!-- Screen readers, SEO, extensions and so on. -->
  3. <html lang="fr">
  4. <!-- Has to be within the first 1024 bytes, hence before the <title>
  5. See: https://www.w3.org/TR/2012/CR-html5-20121217/document-metadata.html#charset -->
  6. <meta charset="utf-8">
  7. <!-- Why no `X-UA-Compatible` meta: https://stackoverflow.com/a/6771584 -->
  8. <!-- The viewport meta is quite crowded and we are responsible for that.
  9. See: https://codepen.io/tigt/post/meta-viewport-for-2015 -->
  10. <meta name="viewport" content="width=device-width,initial-scale=1">
  11. <!-- Required to make a valid HTML5 document. -->
  12. <title>Second-guessing the modern web (archive) — David Larlet</title>
  13. <meta name="description" content="Publication mise en cache pour en conserver une trace.">
  14. <!-- That good ol' feed, subscribe :). -->
  15. <link rel="alternate" type="application/atom+xml" title="Feed" href="/david/log/">
  16. <!-- Generated from https://realfavicongenerator.net/ such a mess. -->
  17. <link rel="apple-touch-icon" sizes="180x180" href="/static/david/icons2/apple-touch-icon.png">
  18. <link rel="icon" type="image/png" sizes="32x32" href="/static/david/icons2/favicon-32x32.png">
  19. <link rel="icon" type="image/png" sizes="16x16" href="/static/david/icons2/favicon-16x16.png">
  20. <link rel="manifest" href="/static/david/icons2/site.webmanifest">
  21. <link rel="mask-icon" href="/static/david/icons2/safari-pinned-tab.svg" color="#07486c">
  22. <link rel="shortcut icon" href="/static/david/icons2/favicon.ico">
  23. <meta name="msapplication-TileColor" content="#f0f0ea">
  24. <meta name="msapplication-config" content="/static/david/icons2/browserconfig.xml">
  25. <meta name="theme-color" content="#f0f0ea">
  26. <!-- Documented, feel free to shoot an email. -->
  27. <link rel="stylesheet" href="/static/david/css/style_2020-06-19.css">
  28. <!-- See https://www.zachleat.com/web/comprehensive-webfonts/ for the trade-off. -->
  29. <link rel="preload" href="/static/david/css/fonts/triplicate_t4_poly_regular.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" crossorigin>
  30. <link rel="preload" href="/static/david/css/fonts/triplicate_t4_poly_bold.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" crossorigin>
  31. <link rel="preload" href="/static/david/css/fonts/triplicate_t4_poly_italic.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)" crossorigin>
  32. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_regular.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  33. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_bold.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  34. <link rel="preload" href="/static/david/css/fonts/triplicate_t3_italic.woff2" as="font" type="font/woff2" media="(prefers-color-scheme: dark)" crossorigin>
  35. <script type="text/javascript">
  36. function toggleTheme(themeName) {
  37. document.documentElement.classList.toggle(
  38. 'forced-dark',
  39. themeName === 'dark'
  40. )
  41. document.documentElement.classList.toggle(
  42. 'forced-light',
  43. themeName === 'light'
  44. )
  45. }
  46. const selectedTheme = localStorage.getItem('theme')
  47. if (selectedTheme !== 'undefined') {
  48. toggleTheme(selectedTheme)
  49. }
  50. </script>
  51. <meta name="robots" content="noindex, nofollow">
  52. <meta content="origin-when-cross-origin" name="referrer">
  53. <!-- Canonical URL for SEO purposes -->
  54. <link rel="canonical" href="https://macwright.org/2020/05/10/spa-fatigue.html">
  55. <body class="remarkdown h1-underline h2-underline h3-underline hr-center ul-star pre-tick">
  56. <article>
  57. <header>
  58. <h1>Second-guessing the modern web</h1>
  59. </header>
  60. <nav>
  61. <p class="center">
  62. <a href="/david/" title="Aller à l’accueil">🏠</a> •
  63. <a href="https://macwright.org/2020/05/10/spa-fatigue.html" title="Lien vers le contenu original">Source originale</a>
  64. </p>
  65. </nav>
  66. <hr>
  67. <main>
  68. <p>The emerging norm for web development is to build a React single-page application, with server rendering. The two key elements of this architecture are something like:</p>
  69. <ol><li>The main UI is built &amp; updated in JavaScript using React or something similar.</li><li>The backend is an API that that application makes requests against.</li></ol>
  70. <p>This idea has really swept the internet. It started with a few major popular websites and has crept into corners like marketing sites and blogs.</p>
  71. <p>I’m increasingly skeptical of it.</p>
  72. <p>There is a sweet spot of React: in moderately interactive interfaces. Complex forms that require immediate feedback, UIs that need to move around and react instantly. That’s where it excels. I helped build the editors in <a href="https://www.mapbox.com/mapbox-studio/">Mapbox Studio</a> and <a href="https://observablehq.com/">Observable</a> and for the most part, React was a great choice.</p>
  73. <p>But there’s a lot on either side of that sweet spot.</p>
  74. <p>The high performance parts aren’t React. <a href="https://docs.mapbox.com/mapbox-gl-js/api/">Mapbox GL</a>, for example, is vanilla JavaScript and probably should be forever. The level of abstraction that React works on is too high, and the cost of using React - in payload, parse time, and so on - is too much for any company to include it as part of an SDK. Same with the <a href="https://github.com/observablehq/runtime">Observable runtime</a>, the juicy center of that product: it’s very performance-intensive and would barely benefit from a port.</p>
  75. <p>The less interactive parts don’t benefit much from React. Listing pages, static pages, blogs - these things are increasingly built in React, but the benefits they accrue are extremely narrow. A lot of the optimizations we’re deploying to speed up these things, things like bundle splitting, server-side rendering, and prerendering, are triangulating what we had before the rise of React.</p>
  76. <p>And they’re kind of messy optimizations. Here are some examples.</p>
  77. <h3 id="bundle-splitting">Bundle splitting.</h3>
  78. <p>As your React application grows, the application bundle grows. Unlike with a traditional multi-page app, that growth affects <em>every visitor</em>: you download the whole app the first time that you visit it. At some point, this becomes a real problem. Someone who lands on the About page is also downloading 20 other pages in the same application bundle. Bundle splitting ‘solves’ this problem by creating many JavaScript bundles that can lazily load each other. So you load the About page and what your browser downloads is an ‘index’ bundle, and then that ‘index’ bundle loads the ‘about page’ bundle.</p>
  79. <p>This <em>sort of</em> solves the problem, but it’s not great. Most bundle splitting techniques require you to load that ‘index bundle’, and then only once that JavaScript is loaded and executed does your browser know which ‘page bundle’ it needs. So you need two round-trips to start rendering.</p>
  80. <p>And then there’s the question of updating code-split bundles. User sessions are surprisingly long: someone might have your website open in a tab for weeks at a time. I’ve seen it happen. So if they open the ‘about page’, keep the tab open for a week, and then request the ‘home page’, then the home page that they request is dictated by <em>the index bundle that they downloaded last week</em>. This is a deeply weird and under-discussed situation. There are essentially two solutions to it:</p>
  81. <ol><li>You keep all generated JavaScript around, forever, and people will see the version of the site that was live at the time of their first page request.</li><li>You create a system that alerts users when you’ve deployed a new version of the site, and prompt them to reload.</li></ol>
  82. <p>The first solution has a drawback that might not be immediately obvious. In those intervening weeks between loading the site and clicking a link, you might’ve deployed a new API version. So the user will be using an old version of your JavaScript frontend with a new version of your API backend, and they’ll trigger errors that none of your testing knows about, because you’ll usually be testing current versions of each.</p>
  83. <p>And the second solution, while it works (and is what we implemented for Mapbox Studio), is a bizarre way for a web application to behave. Prompting users to ‘update’ is something from the bad old days of desktop software, not from the shiny new days of the web.</p>
  84. <p>Sure: traditional non-SPA websites are not immune to this pitfall. Someone might load your website, have a <em>form</em> open for many weeks, and then submit it after their session expired or the API changed. But that’s a much more limited exposure to failure than in the SPA case.</p>
  85. <h3 id="server-side-rendering">Server-Side Rendering</h3>
  86. <p>Okay, so the theory here is that SPAs are initially a blank page, which is then filled out by React &amp; JavaScript. That’s bad for performance: HTML pages don’t <em>need</em> to be blank initially. So, Server-Side Rendering runs your JavaScript frontend code on the backend, creating a filled-out HTML page. The user loads the page, which now has pre-rendered content, and then the JavaScript loads and makes the page interactive.</p>
  87. <p>A great optimization, but again, caveats.</p>
  88. <p>The first is that the page you initially render is dead: you’ve created the <a href="https://web.dev/interactive/">Time To Interactive</a> metric. It’s your startup’s homepage, and it has a “Sign up” button, but until the JavaScript loads, that button doesn’t do anything. So you need to compensate. Either you omit some interactive elements on load, or you try really hard to make sure that the JavaScript loads faster than users will click, or you make some elements not require JavaScript to work - like making them normal links or forms. Or some combination of those.</p>
  89. <p>And then there’s the authentication story. If you do SSR on any pages that are custom to the user, then you need to forward any cookies or authentication-relevant information to your API backend and make sure that you never cache the server-rendered result. Your formerly-lightweight application server is now doing quite a bit of labor, running React &amp; making API requests in order to do this pre-rendering.</p>
  90. <h3 id="apis">APIs</h3>
  91. <p>The dream of APIs is that you have generic, flexible endpoints upon which you can build any web application. That idea breaks down pretty fast.</p>
  92. <p>Most interactive web applications start to triangulate on “one query per page.” API calls being generic or reusable never seems to persist as a value in infrastructure. This is because a large portion of web applications are, at their core, query &amp; transformation interfaces on top of databases. The hardest performance problems they tend to have are query problems and transfer problems.</p>
  93. <p>For example: a generically-designed REST API that tries not to mix ‘concerns’ will produce a frontend application that has to make lots of requests to display a page. And then a new-age GraphQL application will suffer under the <a href="https://engineering.shopify.com/blogs/engineering/solving-the-n-1-problem-for-graphql-through-batching">N+1 query problem</a> at the database level until an optimization arrives. And a traditional “make a query and put it on a page” application will just, well, try to write some good queries.</p>
  94. <p>None of these solutions are silver bullets: I’ve worked with overly-strict REST APIs, optimization-hungry GraphQL APIs, and hand-crafted SQL APIs. But no option really lets a web app be careless about its data-fetching layer. Web applications can’t sit on top of independently-designed APIs: to have a chance at performance, the application and its datasource need to be designed as one.</p>
  95. <h3 id="data-fetching">Data fetching</h3>
  96. <p>Speaking of data fetching. It’s really important and really bizarre in React land. Years ago, I expected that some good patterns would emerge. Frankly, they didn’t.</p>
  97. <p>There are decent patterns in the form of GraphQL, but for a React component that loads data with fetch from an API, the solutions have only gotten weirder. There’s great documentation for everything else, but old-fashioned data loading is relegated to one example of how to mock out ‘fetch’ for testing, and lots of Medium posts of varying quality.</p>
  98. <p><hr/><p>Don’t read this as anti-React. I still think React is pretty great, and for a particular scope of use cases it’s the best tool you can find. And I explicitly want to say that – from what I’ve seen – most other Single-Page-Application tools share most of these problems. They’re issues with the pattern, not the specific frameworks used to implement it. React alternatives have some great ideas, and they might be better, but they are ultimately really similar.</p><p>But I’m at the point where I look at where the field is and what the alternative patterns are – taking a second look at unloved, unpopular, uncool things like Django, Rails, Laravel – and think <em>what the heck is happening</em>. We’re layering optimizations upon optimizations in order to get the SPA-like pattern to fit every use case, and I’m not sure that it is, well, worth it.</p><p><strong>And it should be easy to do a good job.</strong></p><p>Frameworks should lure people into the <a href="https://blog.codinghorror.com/falling-into-the-pit-of-success/">pit of success</a>, where following the normal rules and using normal techniques is the winning approach.</p><p>I don’t think that React, in this context, really is that pit of success. A naïvely implemented React SPA isn’t stable, or efficient, and it doesn’t naturally scale to significant complexity</p><p>You can add optimizations on top of it that fix those problems, or you can use a framework like Next.js that will include those optimizations by default. That’ll help you get pretty far. But then you’ll be lured by all of the easy one-click ways to add bloat and complexity. You’ll be responsible for keeping some of these complex, finicky optimizations working properly.</p><p>And for what? Again - there is a swath of use cases which would be hard without React and which aren’t complicated enough to push beyond React’s limits. But there are also a <em>lot</em> of problems for which I can’t see any concrete benefit to using React. Those are things like blogs, shopping-cart-websites, mostly-<a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a>-and-forms-websites. For these things, all of the fancy optimizations are trying to get you closer to <em>the performance you would’ve gotten if you just hadn’t used so much technology</em>.</p><p>I can, for example, guarantee that this blog is faster than <em>any Gatsby blog</em> (and much love to the Gatsby team) because there is nothing that a React static site can do that will make it faster than a non-React static site.</p><hr/><p>But the cultural tides are <em>strong</em>. Building a company on Django in 2020 seems like the equivalent of driving a PT Cruiser and blasting Faith Hill’s “Breathe” on a CD while your friends are listening to The Weeknd in their Teslas. Swimming against this current isn’t easy, and not in a trendy contrarian way.</p><p>I don’t think that everyone’s using the SPA pattern for no reason. For large corporations, it allows teams to work independently: the “frontend engineers” can “consume” “APIs” from teams that probably work in a different language and can only communicate through the hierarchy. For heavily interactive applications, it has real benefits in modularity, performance, and structure. And it’s beneficial for companies to shift computing requirements from their servers to their customers browsers: a real win for reducing their spend on infrastructure.</p><p>But I think there are a lot of problems that are better solved some other way. There’s no category winner like React as an alternative. Ironically, backends are churning through technology even faster than frontends, which have been loyal to one programming language for decades. There are some age-old technologies like Rails, Django, and Laravel, and there are a few halfhearted attempts to do templating and “serve web pages” from Go, Node, and other new languages. If you go this way, you’re beset by the cognitive dissonance of following in the footsteps of enormous projects - Wikipedia rendering web pages in PHP, Craigslist rendering webpages in Perl - but being far outside the norms of <em>modern web development</em>. If Wikipedia were started today, it’d be React. Maybe?</p><p>What if everyone’s wrong? We’ve been wrong before.</p></p>
  99. </main>
  100. </article>
  101. <hr>
  102. <footer>
  103. <p>
  104. <a href="/david/" title="Aller à l’accueil">🏠</a> •
  105. <a href="/david/log/" title="Accès au flux RSS">🤖</a> •
  106. <a href="http://larlet.com" title="Go to my English profile" data-instant>🇨🇦</a> •
  107. <a href="mailto:david%40larlet.fr" title="Envoyer un courriel">📮</a> •
  108. <abbr title="Hébergeur : Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33184162340">🧚</abbr>
  109. </p>
  110. <template id="theme-selector">
  111. <form>
  112. <fieldset>
  113. <legend>Thème</legend>
  114. <label>
  115. <input type="radio" value="auto" name="chosen-color-scheme" checked> Auto
  116. </label>
  117. <label>
  118. <input type="radio" value="dark" name="chosen-color-scheme"> Foncé
  119. </label>
  120. <label>
  121. <input type="radio" value="light" name="chosen-color-scheme"> Clair
  122. </label>
  123. </fieldset>
  124. </form>
  125. </template>
  126. </footer>
  127. <script type="text/javascript">
  128. function loadThemeForm(templateName) {
  129. const themeSelectorTemplate = document.querySelector(templateName)
  130. const form = themeSelectorTemplate.content.firstElementChild
  131. themeSelectorTemplate.replaceWith(form)
  132. form.addEventListener('change', (e) => {
  133. const chosenColorScheme = e.target.value
  134. localStorage.setItem('theme', chosenColorScheme)
  135. toggleTheme(chosenColorScheme)
  136. })
  137. const selectedTheme = localStorage.getItem('theme')
  138. if (selectedTheme && selectedTheme !== 'undefined') {
  139. form.querySelector(`[value="${selectedTheme}"]`).checked = true
  140. }
  141. }
  142. const prefersColorSchemeDark = '(prefers-color-scheme: dark)'
  143. window.addEventListener('load', () => {
  144. let hasDarkRules = false
  145. for (const styleSheet of Array.from(document.styleSheets)) {
  146. let mediaRules = []
  147. for (const cssRule of styleSheet.cssRules) {
  148. if (cssRule.type !== CSSRule.MEDIA_RULE) {
  149. continue
  150. }
  151. // WARNING: Safari does not have/supports `conditionText`.
  152. if (cssRule.conditionText) {
  153. if (cssRule.conditionText !== prefersColorSchemeDark) {
  154. continue
  155. }
  156. } else {
  157. if (cssRule.cssText.startsWith(prefersColorSchemeDark)) {
  158. continue
  159. }
  160. }
  161. mediaRules = mediaRules.concat(Array.from(cssRule.cssRules))
  162. }
  163. // WARNING: do not try to insert a Rule to a styleSheet you are
  164. // currently iterating on, otherwise the browser will be stuck
  165. // in a infinite loop…
  166. for (const mediaRule of mediaRules) {
  167. styleSheet.insertRule(mediaRule.cssText)
  168. hasDarkRules = true
  169. }
  170. }
  171. if (hasDarkRules) {
  172. loadThemeForm('#theme-selector')
  173. }
  174. })
  175. </script>
  176. </body>
  177. </html>