{"title":"Devel without a Cause Blog","subtitle":"The personal blog of Doug Parker, the \"Devel without a Cause\" about software, frontend, the web, and everything else.","icon":"https:\/\/blog.dwac.dev\/res\/img\/icon.svg","link":[{"@attributes":{"href":"https:\/\/blog.dwac.dev\/feed.xml","rel":"self"}},{"@attributes":{"href":"https:\/\/blog.dwac.dev\/"}}],"updated":"2025-11-01T19:00:00Z","id":"https:\/\/blog.dwac.dev\/","author":{"name":"Doug Parker (Devel without a Cause)","email":"devel@dwac.dev"},"entry":[{"title":"The AI Capability Gap","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/capability-gap\/"}},"updated":"2025-11-01T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/capability-gap\/","content":"<h1 id=\"the-ai-capability-gap\">The AI Capability Gap<\/h1>\n<p>Ever since the launch of ChatGPT, the software industry has, like it or not,\nbeen obsessed with AI and invested millions of dollars into building tools and\ninfrastructure to support it.<\/p>\n<p>I&#39;ve been endlessly fascinated by this for a few reasons beyond the AI features\nthemselves. It feels like we&#39;re in the middle of a very unique time in our\nindustry&#39;s history, one in which we&#39;re quite literally building out an entirely\nnew ecosystem, largely from scratch, at an incredible velocity and scale.<\/p>\n<p>I&#39;m still not very good with AI myself. Frankly, delegating problems to an agent\nmakes me mentally disengage so heavily that literally I start falling asleep at\nmy desk. However, I&#39;ve definitely seen the power of LLMs. Being so heavily\ninvolved in web tooling myself, I&#39;ve been trying to keep up with this space for\na while now and that&#39;s only been accelerated as my day job on\n<a href=\"https:\/\/angular.dev\/\" target=\"_blank\">Angular<\/a> has been pivoting more and more to focus on AI\nintegrations. I&#39;ve been forced to ask myself what kind of AI tooling is\nnecessary to support web frameworks in this new age, which has led me to\nidentify a few key takeaways I want to share here which can help guide our\nthinking about building AI-enabled tooling.<\/p>\n<p>This post itself is a slightly more generic version of a section from our\n<a href=\"https:\/\/youtu.be\/XSfbOT2shyQ?si=hCv9SW92-zh8Ne68&t=1323\" target=\"_blank\">AngularConnect 2025 keynote<\/a>.\nIf you&#39;re not familiar with Angular, don&#39;t worry, this post doesn&#39;t <em>really<\/em>\nhave anything to do with it, beyond some loose examples you don&#39;t really need\nany background to understand.<\/p>\n<h2 id=\"user-types\">User Types<\/h2>\n<p>We have historically had two major types of users for any kind of software:\nhumans and automation.<\/p>\n<ul>\n<li>Humans are those squishy water-filled flesh bags which like rich UI\ninterfaces, well-integrated services, and smooth animations.<ul>\n<li>Examples:<ul>\n<li>You (no really).<\/li>\n<li>That one user who can&#39;t find their phone&#39;s power button.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<li>Automation covers the wide range of code that calls other code. It loves\ndeterminism, well-defined data schemas, and strong API contracts.<ul>\n<li>Examples:<ul>\n<li>A CI (continuous integration) runner.<\/li>\n<li>A cronjob running a task every X hours.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<blockquote>\n<p>Now we have a third type of user: the AI agent.<\/p>\n<\/blockquote>\n<p>This one is a little strange in that it doesn&#39;t follow strict rules like\ntraditional automation and can even reason much like a human, but doesn&#39;t care\nfor UI applications. It is also weirdly non-deterministic and totally ok with\nunstructured data, but has a limited and unreliable memory in the form of a\nconstrained context window.<\/p>\n<p>Which user type you&#39;re targeting to solve a particular problem heavily\ninfluences the kinds of architectural decisions you make and the kind of\nsoftware you ultimately build. This is because each user type works best with\ndifferent <em>API surfaces<\/em>.<\/p>\n<h2 id=\"api-surfaces\">API Surfaces<\/h2>\n<p>A developer, a CI runner, and an AI agent walk into a bar. They each order &quot;One\nbuild please!&quot;<\/p>\n<ul>\n<li>The bartender hands the developer two red squiggly lines and a hundred orange\nones. They sigh and go next door for a coffee.<\/li>\n<li>The bartender gives the CI runner a big red X and a wooden log with errors\netched all over. It neatly organizes the log next to a thousand others.<\/li>\n<li>The bartender tells the AI agent, &quot;Your build failed&quot; and goes on to state\neach error verbally. The AI replies &quot;You&#39;re absolutely right!&quot;<\/li>\n<\/ul>\n<p>The human and automation user types have been around for a long time and, as an\nindustry, we understand pretty well how to build software for them. For humans,\nthis is typically limited to graphical interfaces and some unique accessibility\ndevices, but also developers are comfortable with CLI tools in the right\ncircumstances. Automation works best with CLI tools, libraries in your preferred\nprogramming language, or REST services accessible over a network, among other\noptions.<\/p>\n<p>Each of these is a distinct &quot;API surface&quot; which can be easier or harder to\nconsume for the different user types. Picking the right surface for your\nsolution is critical to meeting your users where they need it.<\/p>\n<p>For example, when the Angular team wanted to provide a tool to build Angular\napplications, we <em>could<\/em> have built a graphical interface where you click a\nbutton each time you want to build your app, but that would have been difficult\nto script and run in CI environments, among a host of other issues. So we didn&#39;t\ndo that, and instead developed <a href=\"https:\/\/angular.dev\/tools\/cli\" target=\"_blank\">Angular CLI<\/a>,\nunderstanding that running <code>ng build<\/code> as a CLI command would work better for\nautomated use cases while still supporting human users in a context where a CLI\ntool would be a fairly reasonable compromise.<\/p>\n<p>But now, we have to consider AI as its own user type.<\/p>\n<p>Continuing the Angular CLI example, <code>ng serve<\/code> runs a devserver in the\nforeground and blocks the terminal until you press <kbd>Ctrl<\/kbd> +\n<kbd>C<\/kbd>. Developers understand this convention and automation can run this\nas a subprocess and send the kill signal when done. Defining our solution&#39;s API\nsurface as a CLI tool has historically been perfectly fine and is how the vast\nmajority of devservers operate.<\/p>\n<p>With AI now in the picture, a new constraint arises. AI agents can generally run\nCLI tools just fine. However, they will typically execute a command in a\nblocking context, waiting for it to complete before finishing. For <code>ng serve<\/code>,\nthe command technically runs forever, and will cause the AI agent to just hang.\nThe agent doesn&#39;t know to kill the process, and the use case breaks.\nSometimes agents are smart enough to run <code>ng serve &amp;<\/code> to execute it in the\nbackground, which avoids hanging the prompt, but then they struggle to see the\noutput of the command which indicates any compile errors which need to be fixed,\nmeaning they lose a critical piece of information normally available to either\nhumans or automation using the same command.<\/p>\n<p>To generalize this example, our existing design uses an API surface which works\nfine for human users and traditional automation, but breaks for AI agents.\nFixing this requires an entirely new API surface for agents to interact with\nwhich is more friendly to their limitations.<\/p>\n<blockquote>\n<p>AI users demand new API surfaces.<\/p>\n<\/blockquote>\n<p>So what kind of API surface makes sense for AI agents?<\/p>\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Model_Context_Protocol\" target=\"_blank\">Model Context Protocol (MCP)<\/a>\nis the most obvious API surface tailored to AI use cases.\n<a href=\"https:\/\/angular.dev\/ai\/mcp\" target=\"_blank\">Angular's MCP server<\/a> exists for this exact reason.<\/p>\n<p>MCP is a great starting point, but as an industry, we have only just begun the\nprocess of building the AI ecosystem and are still figuring out the patterns and\nabstractions which work well for AI agents.<\/p>\n<p>MCP is one of our most foundational tools and yet is still not even a year old\nas of time of writing and many other major problems still remain unsolved. Even\ntoday, I don&#39;t believe we&#39;ve really addressed <em>composability<\/em>, as libraries and\ndependencies cannot define prompts or MCP tools in a way which is consumed\nautomatically without application developers manually enabling them\nindividually. Code inside browser contexts cannot easily communicate with AI\nagents outside of them, siloing a huge part of the web ecosystem off from its AI\ntooling. I&#39;m still not convinced we&#39;ve really figured out how to make MCP\nservices accessible to non-technical users in a generic AI prompt interface.<\/p>\n<p>At a higher-level, we need to rethink the kinds of products and services we are\nbuilding in the first place. Applications are figuring out how best to serve\nusers through chat interfaces. Products need to make their experiences available\nwithin a foreign chat application. <a href=\"https:\/\/chatgpt.com\/atlas\" target=\"_blank\">OpenAI's Atlas<\/a>\nis trying to redefine what it means to be a browser in an LLM world. Everyone\nneeds to figure out how to monetize users trapped within a big tech chat UI.<\/p>\n<p>The progress we&#39;ve made in such a short time is quite amazing, but we must\nrecognize that we are still <em>very<\/em> early in this process and potentially still\nlack the mechanisms which will be considered foundational when we look back on\nAI in 10+ years.<\/p>\n<p>We didn&#39;t figure out UX for humans overnight and many unsolved problems still\nexist. We&#39;re only just now trying to figure out what API surfaces best serve AI\nusers and our journey has just begun.<\/p>\n<p>So if we have and will need additional API surfaces to support AI agents, what\nkind of solutions will we need to provide in the first place? Can we dig deeper\nto understand the core <em>needs<\/em> of AI agents?<\/p>\n<h2 id=\"ai-needs\">AI Needs<\/h2>\n<p>Exactly what functionality your AI agent needs and how it should interact with\nthat functionality is heavily dependent on the precise workflow you&#39;re trying to\nuse AI for. However, any AI workflow likely emulates all or part of existing\nhuman or automation workflows. Based on the context of an existing system, we\ncan look to these human and automated use cases we already support for\ninspiration.<\/p>\n<blockquote>\n<p>Humans and AI have similar needs.<\/p>\n<\/blockquote>\n<p>While AI agents are far from human, I&#39;ve found that they can be surprisingly\n&quot;human&quot; in the way they operate. Both human developers and AI agents want\ndetailed documentation, well-lit paths for common problems, and clean APIs. We\nboth hallucinate from time to time, get frustrated when technology doesn&#39;t work,\nand sometimes make irrational decisions.<\/p>\n<p>My current favorite AI interaction:<\/p>\n<blockquote>\n<p>Me: Hey, this increment button ain&#39;t incrementing, can you fix it?<\/p>\n<p>AI: Hmm, looks like an Angular component but I&#39;m not sure why it wouldn&#39;t\nwork. Must be\n<a href=\"https:\/\/angular.dev\/guide\/components\/advanced-configuration#changedetectionstrategy\" target=\"_blank\">change detection<\/a>,\nI&#39;ll call\n<a href=\"https:\/\/angular.dev\/api\/core\/ChangeDetectorRef#markForCheck\" target=\"_blank\"><code>markForCheck<\/code><\/a>\nand see if that fixes it.<\/p>\n<\/blockquote>\n<p>Never have I felt more seen by a piece of technology.<\/p>\n<p>Using existing human needs as a baseline for AI needs is a great starting point.\nHowever, it potentially limits our imagination of what we can build in the\nfuture based on what&#39;s been possible in the past. How can we take this a step\nfurther to support not just the AI use cases we can envision today, but also set\nup our products for success with the unimaginable workflows we&#39;ll be using\ntomorrow?<\/p>\n<h2 id=\"capabilities\">Capabilities<\/h2>\n<p>This next part requires us to actually narrow our focus down. To stop thinking\nabout these higher-level workflows and instead ask ourselves what humans,\nautomation, and AI agents actually want to <em>do<\/em> down to the smallest scope we\ncan define. Things like, &quot;pull some code&quot;, &quot;run a build&quot;, &quot;brew some coffee&quot;.\nWhat might we call these &quot;things that users want to do&quot;?<\/p>\n<p>We could call them &quot;use cases&quot;, but that&#39;s a bit higher-level abstraction than\nI&#39;m thinking here. A use case has a goal, a purpose which we compose multiple\n&quot;things&quot; to achieve.<\/p>\n<p>We could call it &quot;context&quot;, in that all three of these user types want to know\ncertain aspects about the system, such as current build errors or the currently\nchecked out commit. In some sense, those are both relevant context about the\napplication. There&#39;s an aspect of\n<a href=\"https:\/\/www.anthropic.com\/engineering\/effective-context-engineering-for-ai-agents\" target=\"_blank\">\"context engineering\"<\/a>\nat play here no doubt. However, I think the term &quot;context&quot; is a bit broader than\n&quot;things you can do.&quot; It tends to be a little more readonly than I&#39;m envisioning\nand also covers aspects like historical information about the system&#39;s\ndevelopment, the tech stack in use, the team&#39;s style guide, the architecture,\nand more.<\/p>\n<p>Instead, the word I&#39;m landing on is &quot;capability&quot;.<\/p>\n<blockquote>\n<p>A &quot;capability&quot; is a discrete task which a user, (whether human, automation, or\nAI), can perform.<\/p>\n<\/blockquote>\n<p>This often requires some input data and outputs relevant information about the\nsystem and can be composed to create higher-level capabilities. These range\nfrom:<\/p>\n<ul>\n<li>Read a file from disk.<\/li>\n<li>Make a network request.<\/li>\n<li>Perform a build and receive any errors.<\/li>\n<li>Run tests and receive the results.<\/li>\n<li>Set a breakpoint.<\/li>\n<li>Inspect the current state of a variable.<\/li>\n<\/ul>\n<p>These capabilities define the core actions available to a user and are the\nfundamental primitives which can be composed to achieve larger capabilities and\neventually a higher-level workflow. For example, as a human you can fix a bug\nusing a workflow from the standard software development lifecycle:<\/p>\n<ol>\n<li>Read the Jira ticket.<\/li>\n<li>Pull the latest copy of the code.<\/li>\n<li>Start the application.<\/li>\n<li>Fail to reproduce the issue.<\/li>\n<li>Close the bug as not reproducible.<\/li>\n<li>Get notified when your boss reopens the issue.<\/li>\n<li>Actually reproduce it.<\/li>\n<li>Debug the problem.<\/li>\n<li>Wonder how it ever worked in the first place.<\/li>\n<li>Write some new code.<\/li>\n<li>Test it.<\/li>\n<li>Merge it.<\/li>\n<\/ol>\n<p>This workflow is a combination of smaller capabilities you, as a human, are able\nto perform. Each of them is a capability an AI agent will benefit from to create\nits own workflows, whether identical to this one, a subset of it, or something\ncompletely different.<\/p>\n<p>As a tooling engineer focused on integrating disparate systems into a cohesive\nexperience, the features I actually build are often these capabilities, core\nprimitive functions and connections. Capabilities support higher-level workflows\nand use cases, both ones I can imagine and am building for today, as well as\nthose I can&#39;t and which can surface organically from the same implementations.<\/p>\n<p>Therefore I believe most products should focus on designing and building these\ncore capabilities while allowing AI agents to compose them into more\ncomprehensive workflows. There&#39;s a broader discussion around what designing\nthese workflows actually looks like and the experiences you can create with\nthem, but here I&#39;m focused on the lower-level tooling integrations, so I&#39;ll\nleave that out of scope for now.<\/p>\n<h2 id=\"capability-parity\">Capability Parity<\/h2>\n<p>This leads to the next point I want to make: All user types (humans, automation,\nand AI agents) should have parity across their raw capabilities. Or put another\nway:<\/p>\n<blockquote>\n<p>Anything a human can do, an AI should be able to do too.<\/p>\n<\/blockquote>\n<p>Aligning capabilities between the different user types enables AI agents to be\njust as powerful as humans or traditional automation. When we lose this parity,\nwe end up asking AI to solve problems it is fundamentally unprepared to solve,\nmuch like bringing in a contractor to fix a bug without giving them access to\nthe source code containing it.<\/p>\n<p>What often looks like an AI just not being intelligent enough to solve a problem\ncan often be attributed to the AI doing the best it can with the limited\ncapabilities provided to it. You can open your browser and see that a button is\nclearly not centered and look at DevTools to understand which style might be\ncausing that. But if your AI does not have that same capability, it is left\nguessing as to what might be causing a behavior it can&#39;t even observe in the\nfirst place. You would probably struggle the same way if you were forced to\ndebug such an issue from looking only at source code. In this way, providing an\nAI the right capabilities directly impacts its ability to intelligently reason\nabout a problem and find the right solution.<\/p>\n<p>I think this idea of capability parity has actually been pretty well-known for a\nwhile, just without the AI agent part. If you build a UI to do something,\neventually some power user is going to ask for a script or API so they can\nautomate the same process. There&#39;s already a desire to align these capabilities\nacross humans and automation, AI is just adding one more user type.<\/p>\n<p>Now I feel compelled to add a few qualifiers here:<\/p>\n<p>First, AI agents should still be subject to the same constraints a human would.\nFor example, most mature organizations do not allow developers to merge a PR or\npush to prod unrestricted. You first need tests to pass and a bribe for your\ntech lead to approve it. So notably, those are both capabilities which humans\ngenerally <em>do not<\/em> have and therefore do not need to be given to AI without\ncomparable constraints.<\/p>\n<p>Second, we don&#39;t necessarily need the <em>a single<\/em> AI to have access to all of\nthese capabilities. The AI helping you write code and the AI triaging bugs don&#39;t\nneed equivalent capabilities. In fact, providing too many capabilities may have\nthe opposite effect of distracting it into the wrong workflow for the problem at\nhand. The point here is that <em>some<\/em> AI has the capability you need in a context\nyou can leverage effectively.<\/p>\n<p>Third, don&#39;t take this too seriously. All absolute statements are false and I&#39;m\ntalking mainly in the context of software engineering here. Trust and safety is\na thing for a reason. Please don&#39;t give your AI the capability to launch a nuke,\nuse some common sense.<\/p>\n<p>The main argument here is that we can use existing capabilities provided to\nhumans and traditional automation as inspiration for capabilities we want to\nprovide to AI agents while still supporting novel workflows which compose them\nin unique and interesting ways.<\/p>\n<h2 id=\"the-capability-gap\">The Capability Gap<\/h2>\n<p>The language of &quot;capabilities&quot; also allows us to define the scope of all &quot;human\ncapabilities&quot; and currently feasible &quot;AI capabilities&quot; being the full set of\nactions either user type can perform. Comparing these two allows us to define...<\/p>\n<blockquote>\n<p>The &quot;capability gap&quot; is the set of actions a human can perform but an AI\ncannot.<\/p>\n<\/blockquote>\n<p>Since the goal is overall parity, this gap should be eliminated entirely, or at\nleast close to eliminated.<\/p>\n<p>I suspect over the next decade, a main focus of our industry will be closing\nthis capability gap, finding all those little features and filling in the bells\nand whistles to make AI agents as powerful as individual developers.<\/p>\n<p>Capabilities within this gap aren&#39;t just a superiority complex for developers;\nthey represent a human tax placed on any workflow that exercises them. Any time\nan AI workflow requires a capability it doesn&#39;t have, it is forced to use a\nless-effective alternative (breakpoints vs. <code>printf<\/code> debugging), or I as the\nhuman driver need to step in and perform that work for it.<\/p>\n<p>As an overly-simplified example, if an  AI can&#39;t see error messages, then it is\nmy responsibility to find and copy-paste those messages into the prompt. There&#39;s\nno intelligence, engineering, or meaningful knowledge work here; there is only\ntoil to serve the needs of my personal AI overlord. I have become a\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Mechanical_Turk\" target=\"_blank\">mechanical turk<\/a>, a function\nimplemented not of ones and zeros but of clicks and key presses, invoked by an\nautonomous being from a higher plane. My only salvation is to empower that being\nso it no longer demands physical labor from me such that I may think for myself\nwhen it chooses to spare me by placing its attention elsewhere.<\/p>\n<p>Sorry, I was spacing out there for a second...<\/p>\n<p>The point is, there is a huge opportunity space for developers and startups to\nidentify missing capabilities and build out the tooling and integrations\nnecessary to support them. Don&#39;t limit yourself by thinking &quot;eh, someone&#39;s\nalready solving these problems&quot;. I guarantee you there are gaps no one is\nthinking about yet where you can find your niche.<\/p>\n<p>Ultimately, I don&#39;t think anything in this post is all that innovative. Gemini\nsummarizes it, quite correctly, as: &quot;For AI to be truly useful, we need to build\nnew tools and APIs to give it the same &#39;capabilities&#39; as a human developer,\notherwise we&#39;re just stuck being glorified assistants for our new robot\noverlords.&quot; That probably isn&#39;t a discovery that&#39;s going to win me a Nobel\nprize.<\/p>\n<p>But as <a href=\"https:\/\/bsky.app\/profile\/jelbourn.bsky.social\" target=\"_blank\">Jeremy Elbourn<\/a> would put\nit, &quot;Naming something gives you power over it.&quot; This is true in a\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/True_name\" target=\"_blank\">mystical sense<\/a> as well as an\nengineering one. Being able to concretely define a concept enables you to reason\nrationally about it.<\/p>\n<p>To that end, I hope that better defining our three user types, their API\nsurfaces, capabilities, and the capability gap can help change the way you think\nabout AI and how you move forward in this new era.<\/p>\n"},{"title":"Isolating CSS Inheritance","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/"}},"updated":"2025-09-07T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/","content":"<h1 id=\"isolating-css-inheritance\">Isolating CSS Inheritance<\/h1>\n<p>I was recently looking into CSS isolation between multiple applications running\non the same web page and it turned into a deep dive of the CSS <code>initial<\/code> and\n<code>revert<\/code> keywords which I wanted to share in a short post on the subject (short\nfor my blog anyways).<\/p>\n<h2 id=\"the-problem\">The Problem<\/h2>\n<p>I was tasked with running multiple web applications on the same page at the same\ntime. These applications are decoupled from one another, developed by different\nteams, deployed independently at different times, and built from different\ncommits. Effectively a <a href=\"https:\/\/micro-frontends.org\/\" target=\"_blank\">microfrontend<\/a> deployment.<\/p>\n<p>Given this setup, how can we ensure that internal CSS styling from one app does\nnot unexpectedly leak into the other? To make this even more complicated, this\nparticular use case allows one application to be rendered <em>inside<\/em> another,\nmeaning CSS properties may inherit across applications.<\/p>\n<p>The team building the &quot;parent&quot; application might write:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>parent-root<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">color<\/span><span class=\"token punctuation\">:<\/span> red<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>I'm red, just like I expected!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n    ${renderChildApp()}\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>And then the team maintaining the &quot;child&quot; application might write:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>I expect to default to black.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>In isolation, both of these look perfectly reasonable. But when rendered\ntogether, we can see:<\/p>\n<figure>\n    <figcaption>Example 1: Leaking Properties.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token comment\">&lt;!-- Parent application --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>parent-root<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">color<\/span><span class=\"token punctuation\">:<\/span> red<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>I'm red, just like I expected!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n    <span class=\"token comment\">&lt;!-- Child application --><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>I'm red? I expected to default to black.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><!-- Parent application -->\n<div style=\"color: red;\">\n    <div>I'm red, just like I expected!<\/div>\n\n    <!-- Child application -->\n    <div>\n        <div>I'm red? I expected to default to black.<\/div>\n    <\/div>\n<\/div><\/figure>\n\n<p>Because these apps are independently built and deployed, they should be\ngenerally isolated from each other, and arbitrary internal changes in one app\n(such as text color) should not affect the other.<\/p>\n<p>However in this case, the parent&#39;s <code>color: red;<\/code> style is inherited into the\nchild app and colors its text. This style is effectively <em>leaked<\/em> across\napplications.<\/p>\n<p>Now there are numerous ways styles can leak from application to another, all of\nwhich require unique solutions. But for this post, we&#39;ll just focus on CSS\ninheritance. So what can we do to <em>isolate<\/em> these two apps from each other?<\/p>\n<p>Also if your first thought was to reach for shadow DOM or <code>@scope<\/code>, I&#39;m afraid\nneither are viable alternatives for this particular problem due to the focus on\nCSS inheritance specifically (explanation of\n<a href=\"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/#shadow-dom\">shadow DOM<\/a> and <a href=\"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/#scope\"><code>@scope<\/code><\/a> insufficiencies).<\/p>\n<h2 id=\"overrides\">Overrides<\/h2>\n<p>The immediately obvious answer is to override <code>color: black;<\/code> on the child app\nroot.<\/p>\n<figure>\n    <figcaption>Example 2: Overriding <code>color<\/code>.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>parent-root<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">color<\/span><span class=\"token punctuation\">:<\/span> red<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">color<\/span><span class=\"token punctuation\">:<\/span> black<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>I'm black!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div style=\"color: red;\">\n    <div style=\"color: black;\">\n        <div>I'm black!<\/div>\n    <\/div>\n<\/div><\/figure>\n\n<p>But listing out every CSS property and its default value is quite complicated\nand tedious.<\/p>\n<h2 id=\"all\"><code>all<\/code><\/h2>\n<p>Fortunately, CSS has a useful property for this very problem.\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/all\" target=\"_blank\"><code>all<\/code><\/a> applies\na single value to <em>all<\/em> CSS properties (with some minor exceptions) for a\nparticular element.<\/p>\n<p>Each CSS property has a different type, meaning there is no specific value you\ncan provide which is meaningful to <em>every<\/em> property. But there a few CSS base\nkeywords you can use which do apply to every property.<\/p>\n<ul>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/initial\" target=\"_blank\"><code>initial<\/code><\/a><\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/inherit\" target=\"_blank\"><code>inherit<\/code><\/a><\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/unset\" target=\"_blank\"><code>unset<\/code><\/a><\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/revert\" target=\"_blank\"><code>revert<\/code><\/a><\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/revert-layer\" target=\"_blank\"><code>revert-layer<\/code><\/a><\/li>\n<\/ul>\n<p>So which of these would be appropriate in this scenario? A few can be\nimmediately excluded.<\/p>\n<p><code>inherit<\/code> explicitly opts in to the inheritance behavior we <em>don&#39;t<\/em> want.<\/p>\n<p><code>unset<\/code> is equivalent to <code>inherit<\/code> when applied to inherited properties, and\nequivalent to <code>initial<\/code> for non-inherited properties. Again, this explicitly\nopts in to inheritance we&#39;re trying to avoid. And if the <code>initial<\/code> behavior is\nwhat we want, we should just use that directly.<\/p>\n<p><code>revert-layer<\/code> lets you roll back styles from an <code>@layer<\/code>. This is actually\ncloser to workable than you might initially think, but ultimately\n<a href=\"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/#revert-layer\">does not fit this use case<\/a>.<\/p>\n<p>So that leaves us with <code>initial<\/code> and <code>revert<\/code> as potential candidates. Let&#39;s\nlook at each.<\/p>\n<h2 id=\"initial\"><code>initial<\/code><\/h2>\n<p><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/initial\" target=\"_blank\">From MDN:<\/a><\/p>\n<blockquote>\n<p>The <code>initial<\/code> CSS keyword applies the initial (or default) value of a property\nto an element.<\/p>\n<\/blockquote>\n<p>Every CSS property has a default value and setting it to <code>initial<\/code> uses the\ndefault value for its associated property.<\/p>\n<p>Let&#39;s look at <code>display<\/code> as an example. The default value of <code>display<\/code>\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/display#formal_definition\" target=\"_blank\">according to the CSS spec<\/a>\nis <code>inline<\/code>. So setting <code>display: initial;<\/code> is equivalent to <code>display: inline;<\/code>.<\/p>\n<p>You might be surprised to hear that <code>inline<\/code> is the default and not <code>block<\/code>,\nhowever that&#39;s likely because you&#39;re thinking of <code>div<\/code>, which is an exception\nwe&#39;ll get to shortly. Create an element with an arbitrary tag name like\n<code>my-random-element<\/code> and check DevTools. You can confirm the default is indeed\n<code>display: inline;<\/code>. This is the reason so many components include\n<code>:host { display: block; }<\/code> in their styles.<\/p>\n<p>In the context of <code>all: initial;<\/code>, we&#39;re using the default value for every\nproperty as specified by the CSS standard.<\/p>\n<h2 id=\"revert\"><code>revert<\/code><\/h2>\n<p>So what about <code>revert<\/code>?<\/p>\n<p><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/revert\" target=\"_blank\">Also from MDN<\/a>:<\/p>\n<blockquote>\n<p>The <code>revert<\/code> CSS keyword reverts the cascaded value of the property from its\ncurrent value to the value the property would have had if no changes had been\nmade by the current style origin to the current element. Thus, it resets the\nproperty either to user agent set value, to user set value, to its inherited\nvalue (if it is inheritable), or to initial value.<\/p>\n<\/blockquote>\n<p>And that&#39;s a little more involved... Let me try and break this down a bit.<\/p>\n<p>This description mentions a &quot;user agent set value&quot;, and to understand that, we\nneed to first discuss the user-agent stylesheet.<\/p>\n<h3 id=\"style-origins\">Style Origins<\/h3>\n<p>The first definition to understand here is &quot;style origin&quot;. This refers to the\ndifferent locations CSS can come from.<\/p>\n<blockquote>\n<p>if no changes had been made by the current style origin to the current element<\/p>\n<\/blockquote>\n<p>This is talking about styles originating from the current document, basically\nall the CSS you think of as your application&#39;s styles, anything in a <code>&lt;style&gt;<\/code>\nor <code>&lt;link rel=&quot;stylesheet&quot;&gt;<\/code> you&#39;ve inserted into the page. <code>revert<\/code> pretends\nnone of these application styles exist and instead reverts to...<\/p>\n<h3 id=\"the-user-agent-stylesheet\">The User-Agent Stylesheet<\/h3>\n<p>Every browser includes a\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/CSS_cascade\/Cascade#user-agent_stylesheets\" target=\"_blank\">\"user-agent stylesheet\"<\/a>\n(UA stylesheet), this is an additional set of CSS styles applied to all web\npages with some browser-specific styling.<\/p>\n<p>This stylesheet is why a plain <code>&lt;button&gt;<\/code> element with no CSS looks just a\n<em>little<\/em> different between browsers in order to match the system UI users expect\non their particular platform. For example, consider the visual design of a\ndefault button on desktop Windows vs mobile iOS. Those differences are managed\nby the UA stylesheet.<\/p>\n<p>These UA styles are literally defined as a stylesheet, and you can observe it in\nDevTools or by just looking at\n<a href=\"https:\/\/source.chromium.org\/chromium\/chromium\/src\/+\/main:third_party\/blink\/renderer\/core\/html\/resources\/html.css;drc=5606f221713df59faee4d92851998db4d9d15aeb\" target=\"_blank\">browser source code<\/a>.\nThis is also how the <code>display<\/code> exception for <code>div<\/code> exception gets handled.\nBrowsers include in their user-agent stylesheet:<\/p>\n<pre><code class=\"language-css\"><span class=\"token selector\">div<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> block<span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>The UA stylesheet is why <code>div<\/code> elements always default to <code>block<\/code>, even though\nthe <code>initial<\/code> value of <code>display<\/code> is actually <code>inline<\/code>.<\/p>\n<p>There is also a &quot;user&quot; style origin where browsers and extensions allow you to\napply your own stylesheet to every page you visit.<\/p>\n<p>In building our microfrontend web application, we want to respect the user&#39;s\nintent and configured settings. If they have configured their browser with\nsomething like <code>h1 { color: magenta; }<\/code> because they like their headers to be\nreally bright and colorful, then more power to them, and our website should\nfollow that preference.<\/p>\n<p>Stepping back to <code>revert<\/code>, recall that it resets to the &quot;user agent set value&quot;,\nmeaning it resets a CSS property to its default\n<em>after taking the user-agent stylesheet into account<\/em>.<\/p>\n<p>We can demonstrate the difference with <code>initial<\/code> using the <code>div<\/code> example:<\/p>\n<figure>\n    <figcaption>\n        Example 3: <code>display: initial;<\/code> vs\n        <code>display: revert;<\/code>.\n    <\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token comment\">&lt;!-- Two elements stack horizontally because they're `inline`. --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> initial<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>I'm <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>inline<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> initial<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>I'm to the side!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>br<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>br<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token comment\">&lt;!-- Two elements stack vertically because they're `block`. --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> revert<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>I'm <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>block<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> revert<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>I'm underneath!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div style=\"display: initial;\">I'm <code>inline<\/code>!<\/div>\n<div style=\"display: initial;\">I'm to the side!<\/div>\n\n<br \/><br \/>\n\n<div style=\"display: revert;\">I'm <code>block<\/code>!<\/div>\n<div style=\"display: revert;\">I'm underneath!<\/div><\/figure>\n\n<p>Based on this description and our desire to respect the user-agent stylesheet,\nit seems like the obvious answer to isolating CSS inheritance is <code>all: revert;<\/code>\nrather than <code>all: initial;<\/code>, right?<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/post-done.avif\" type=\"image\/avif\" width=\"500\" height=\"500\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/post-done.webp\" alt=\"A meme of Anakin and Padme from Star Wars, Attack of the Clones. The two sit in a field as Anakin states matter-of-factly &quot;`all: revert;` sounds reasonable.&quot; Padme responds with a smile, &quot;So this blog post is done, right?&quot; Anakin sits silently for a moment as Padme's expression changes to one of worry and repeats, &quot;So this blog post is done, right?&quot;\" width=\"500\" height=\"500\" decoding=\"async\" loading=\"eager\" fetchpriority=\"high\" \/>\n<\/picture><\/p>\n<h2 id=\"initial-vs-revert\"><code>initial<\/code> vs <code>revert<\/code><\/h2>\n<p>Well, let&#39;s break down a few sub-cases and see what actually happens in\npractice.<\/p>\n<h3 id=\"non-inherited-properties\">Non-Inherited Properties<\/h3>\n<p>Let&#39;s start with non-inherited properties. Much like how every property has a\ndefined <code>initial<\/code> value, each property is defined as either inherited or not.\n<code>display<\/code> for instance is\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/display#formal_definition\" target=\"_blank\">not inherited<\/a>.<\/p>\n<figure>\n    <figcaption>Example 4: Non-Inherited CSS.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>parent-root<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> inline-block<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root-initial<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">all<\/span><span class=\"token punctuation\">:<\/span> initial<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>initial<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>: I'm still\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>block<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>!\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>I'm underneath the block.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>br<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root-revert<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">all<\/span><span class=\"token punctuation\">:<\/span> revert<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>revert<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>: I'm still\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>block<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>!\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>I'm also underneath the block.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div style=\"display: inline-block;\">\n    <div style=\"all: initial;\">\n        <div>\n            <code>initial<\/code>: I'm still\n            <code>block<\/code>!\n        <\/div>\n        <div>I'm underneath the block.<\/div>\n    <\/div>\n\n    <br \/>\n\n    <div style=\"all: revert;\">\n        <div>\n            <code>revert<\/code>: I'm still\n            <code>block<\/code>!\n        <\/div>\n        <div>I'm also underneath the block.<\/div>\n    <\/div>\n<\/div><\/figure>\n\n<p>In this case, <code>initial<\/code> vs <code>revert<\/code> doesn&#39;t actually make a difference! Since\n<code>display<\/code> isn&#39;t inherited, the <code>inline-block<\/code> on <code>#parent-root<\/code> <em>only<\/em> applies\nto that element. All leaf <code>&lt;div&gt;<\/code> elements ultimately use <code>block<\/code>.<\/p>\n<p>The one difference is that <code>#child-root-initial<\/code> is actually <code>inline<\/code> (uses the\ndefault value of <code>display<\/code>), while <code>#child-root-revert<\/code> is <code>block<\/code> (uses the UA\nstylesheet). But ultimately this is just the container element intended to\ndivide the two apps and we can use whatever display value we want. We could just\nas easily get the opposite behavior by explicitly specifying <code>display<\/code>:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root-initial<span class=\"token punctuation\">\"<\/span><\/span>\n        <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">all<\/span><span class=\"token punctuation\">:<\/span> initial<span class=\"token punctuation\">;<\/span> <span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> block<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token comment\">&lt;!-- ... --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root-revert<span class=\"token punctuation\">\"<\/span><\/span>\n        <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">all<\/span><span class=\"token punctuation\">:<\/span> revert<span class=\"token punctuation\">;<\/span> <span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> inline<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token comment\">&lt;!-- ... --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Either approach flips the <code>display<\/code> value of the container without affecting any\ndescendant elements. So from an isolation perspective, this is a fairly\nirrelevant difference.<\/p>\n<p>So there is no meaningful difference between <code>initial<\/code> and <code>revert<\/code> with respect\nto non-inherited properties. Inherited properties get a bit more complicated, so\nlet&#39;s break down a few more use cases.<\/p>\n<h3 id=\"inherited-properties-on-ua-elements\">Inherited Properties <em>on<\/em> UA Elements<\/h3>\n<p>The next case to consider are inherited properties on elements directly affected\nby the UA stylesheet. For example,\n<a href=\"https:\/\/source.chromium.org\/chromium\/chromium\/src\/+\/main:third_party\/blink\/renderer\/core\/html\/resources\/html.css;l=175;drc=5606f221713df59faee4d92851998db4d9d15aeb\" target=\"_blank\">Chrome defines<\/a>:<\/p>\n<pre><code class=\"language-css\"><span class=\"token selector\">h1<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token property\">font-weight<\/span><span class=\"token punctuation\">:<\/span> bold<span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Note that\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/font-weight\" target=\"_blank\"><code>font-weight<\/code><\/a>\nis an inherited property with an <code>initial<\/code> value of <code>normal<\/code>.<\/p>\n<p>So how do ancestor styles affect <code>font-weight<\/code> on an <code>h1<\/code> tag? Actually not at\nall.<\/p>\n<figure>\n    <figcaption>Example 5: Inherited on UA Element<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">font-weight<\/span><span class=\"token punctuation\">:<\/span> normal<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>h1<\/span><span class=\"token punctuation\">><\/span><\/span>I'm bold!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>h1<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div style=\"font-weight: normal;\">\n    <!-- The title of the post is already an h1 tag, so we don't want to confuse\n    search engines with a second. `role=\"none\"` should address that. -->\n    <h1 role=\"none\">I'm bold!<\/h1>\n<\/div><\/figure>\n\n<p>Since the UA stylesheet explicitly defines <code>font-weight: bold;<\/code> through an\n<code>h1<\/code> selector, the property is applied <em>directly<\/em> to the <code>h1<\/code> element.\nTherefore, there is no need for the browser to check ancestors and no way to\naccidentally inherit another value.<\/p>\n<p>So there is no difference between <code>initial<\/code> and <code>revert<\/code> for inherited\nproperties <em>on<\/em> elements with UA styles, as inheritance doesn&#39;t affect this use\ncase at all.<\/p>\n<h3 id=\"inherited-properties-from-ua-elements\">Inherited Properties <em>from<\/em> UA Elements<\/h3>\n<p>The next example inverts the previous one. Instead of putting <code>initial<\/code> or\n<code>revert<\/code> directly <em>on<\/em> an element with an inherited UA style, we reset an\nelement which inherits <em>from<\/em> an ancestor element with a UA style.<\/p>\n<figure>\n    <figcaption>Example 6: Inherited from UA Element<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>parent-root<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>h1<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Parent: I inherited bold!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root-initial<span class=\"token punctuation\">\"<\/span><\/span>\n                <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">font-weight<\/span><span class=\"token punctuation\">:<\/span> initial<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>initial<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span> child: I'm <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>em<\/span><span class=\"token punctuation\">><\/span><\/span>not<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>em<\/span><span class=\"token punctuation\">><\/span><\/span> bold!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root-revert<span class=\"token punctuation\">\"<\/span><\/span>\n                <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">font-weight<\/span><span class=\"token punctuation\">:<\/span> revert<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>revert<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span> child: I'm still bold!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>h1<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div>\n    <!-- The title of the post is already an h1 tag, so we don't want to confuse\n    search engines with a second. `role=\"none\"` should address that. -->\n    <h1 role=\"none\">\n        <div>Parent: I inherited bold!<\/div>\n\n        <div style=\"font-weight: initial;\">\n            <div><code>initial<\/code> child: I'm <em>not<\/em> bold!<\/div>\n        <\/div>\n\n        <div style=\"font-weight: revert;\">\n            <div><code>revert<\/code> child: I'm still bold!<\/div>\n        <\/div>\n    <\/h1>\n<\/div><\/figure>\n\n<p>This example begs the question: Do we <em>want<\/em> the child app to be bold in this\nscenario?<\/p>\n<p>I can actually see arguments for yes and no. Since the parent and child\napplications are intended to be independently developed by different teams and\ndeployed with minimal coupling, there is no way for the child app to know\nwhether or not it will be loaded in a bold <code>h1<\/code> tag or any other tag. This\npresents a hazard, where the parent might incorrectly render the child in a\ncontext it did not expect and the UA styles from that context break the intended\nstyling of the child application. <code>initial<\/code> solves this problem and keeps the\nchild application looking the way its developers intended.<\/p>\n<p>The alternative argument is that the parent has decided to render the child\napplication inside an <code>h1<\/code> tag, explicitly believing this child to make sense in\nthat context. If the child app is genuinely just rendering some title text, then\n<code>revert<\/code> would correctly retain the user&#39;s desired bold behavior. The parent app\nis somewhat implicitly configuring the child app to follow the UA&#39;s styling.<\/p>\n<p>This is a bit of an academic argument, since it is hard to imagine a valid use\ncase for rendering a completely different application inside an <code>h1<\/code> tag.\nSkimming over other styles in Chrome&#39;s UA stylesheet, there&#39;s honestly not many\ninherited properties in there, and the ones which are present tend to be on\n&quot;leaf&quot; elements like <code>&lt;input&gt;<\/code> or <code>&lt;select&gt;<\/code>. So the practical situations in\nwhich this matters are unlikely to ever come up in practice.<\/p>\n<p>Of course, Chrome is only one browser, and others may use more inherited\nproperties or some users \/ tools may expressly customize their UA stylesheet\nwith more inherited properties where this might be more of a practical issue.<\/p>\n<h3 id=\"non-ua-inherited-properties\">Non-UA Inherited Properties<\/h3>\n<p>You might have noticed that I didn&#39;t use <code>color<\/code> in any of the above demos,\ndespite typically being the most immediately obvious inherited property. That&#39;s\nbecause\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/color\" target=\"_blank\"><code>color<\/code><\/a>\nhits one final use case I want to discuss here.<\/p>\n<p>Let&#39;s try the same demo with <code>color<\/code>:<\/p>\n<figure>\n    <figcaption>Example 7: Non-UA Inherited Properties.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>parent-root<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">color<\/span><span class=\"token punctuation\">:<\/span> red<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Parent: I inherit red!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root-initial<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">color<\/span><span class=\"token punctuation\">:<\/span> initial<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>initial<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span> child: I default to black.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root-revert<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">color<\/span><span class=\"token punctuation\">:<\/span> revert<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span>revert<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>code<\/span><span class=\"token punctuation\">><\/span><\/span> child: I inherit red?!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div style=\"color: red;\">\n    <div>Parent: I inherit red!<\/div>\n\n    <div style=\"color: initial;\">\n        <div><code>initial<\/code> child: I default to black.<\/div>\n    <\/div>\n\n    <div style=\"color: revert;\">\n        <div><code>revert<\/code> child: I inherit red?!<\/div>\n    <\/div>\n<\/div><\/figure>\n\n<p><code>initial<\/code> seems to be doing its job and isolating from the parent&#39;s\n<code>color: red;<\/code> style.<\/p>\n<p>However, this <code>revert<\/code> ain&#39;t reverting, so what&#39;s going on? Well, let&#39;s look at\nthe\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/revert\" target=\"_blank\">definition of <code>revert<\/code><\/a>\nonce more (emphasis mine):<\/p>\n<blockquote>\n<p>[<code>revert<\/code>] resets the property either to user agent set value, to user set\nvalue, <strong>to its inherited value (if it is inheritable)<\/strong>, or to initial value.<\/p>\n<\/blockquote>\n<p>So <code>revert<\/code> prefers the UA stylesheet when it configures the property, but for\nany properties <em>not<\/em> set through the UA stylesheet, it will inherit from its\nancestors before using the <code>initial<\/code> value.<\/p>\n<p>You might expect something like <code>html { color: black; }<\/code> in the UA stylesheet,\nbut this is not the case.\n<a href=\"https:\/\/source.chromium.org\/chromium\/chromium\/src\/+\/main:third_party\/blink\/renderer\/core\/html\/resources\/html.css;drc=5606f221713df59faee4d92851998db4d9d15aeb\" target=\"_blank\">Chrome's UA stylesheet<\/a>\nhas some usage of <code>color<\/code> in certain form elements, but there is no general\n&quot;use <code>black<\/code> as the default text color&quot; style. The default value of <code>color<\/code> is\nhandled through a different abstraction than UA stylesheets. So it is\neffectively defaulting to its <code>initial<\/code> behavior, how does that work for\n<code>color<\/code>?<\/p>\n<p>The <code>initial<\/code> value of <code>color<\/code> is something called <code>CanvasText<\/code>, one of many\n<a href=\"https:\/\/css-tricks.com\/system-things\/\" target=\"_blank\">\"system colors\"<\/a> in the browser. This\none essentially represents the current text color. The actual observed default\nvalue is typically <code>black<\/code>, but this can vary based on configuration. For\nexample, if you enable\n<a href=\"https:\/\/developer.chrome.com\/blog\/auto-dark-theme\" target=\"_blank\">automatic dark theme<\/a> in\nChrome, <code>CanvasText<\/code> switches to <code>white<\/code>, while <code>Canvas<\/code> (basically the\nbackground color) switches from <code>white<\/code> to <code>black<\/code> to create a dark theme.<\/p>\n<p>Since this default <code>color<\/code> value is managed at a different layer, it does not\nappear in the UA stylesheet, therefore <code>revert<\/code> moves on to check if the\nproperty is inherited. Since <code>color<\/code> is inherited, <code>revert<\/code> chooses to inherit\nthe value rather than reset it to its <code>initial<\/code>. Therefore in the above example,\nthe child app incorrectly inherits the <code>red<\/code> color from its parent rather than\nusing the default <code>black<\/code>.<\/p>\n<p>So <code>revert<\/code> does not isolate any inherited properties inherited from outside the\nUA stylesheet.<\/p>\n<h2 id=\"takeaways\">Takeaways<\/h2>\n<p>After building a deeper understanding of the nuances here, it is clear that\n<code>all: initial;<\/code> is the best approach to reset styles and isolate applications.<\/p>\n<p>My biggest surprise from this investigation was how little the difference\nbetween <code>initial<\/code> and <code>revert<\/code> actually is. The only two cases this comes into\nplay is:<\/p>\n<ol>\n<li>Inheriting a property <em>from<\/em> an ancestor element with a UA style.<ul>\n<li>Such a situation just doesn&#39;t come up as often as you might think given\nthe general lack of inherited properties in the UA stylesheet.<\/li>\n<\/ul>\n<\/li>\n<li>Inheriting a property which is <em>not<\/em> in the UA stylesheet for any ancestor\nelements.<\/li>\n<\/ol>\n<p>If you&#39;re trying to reset a specific property on a specific element, I suspect\n<code>revert<\/code> is likely closer to what you&#39;d want most of the time, given the way it\nrespects the UA stylesheet.<\/p>\n<p>But if you&#39;re trying to reset all properties (and thus, likely trying to isolate\na subtree from CSS inheritance), you really want <code>initial<\/code> largely because\n<code>revert<\/code> just becomes <code>inherit<\/code> for any non-UA styles.<\/p>\n<h3 id=\"could-we-create-a-better-option\">Could we Create a Better Option?<\/h3>\n<p>Writing this out now, it seems counter-intuitive that <code>revert<\/code> effectively acts\nlike <code>inherit<\/code> for anything not in the UA stylesheet, especially since any\nwell-behaved web page generally should not require knowledge of the UA\nstylesheet and remain compatible with whatever an arbitrary browser might use.\nBut if you&#39;re using <code>revert<\/code>, you are likely trying to opt-out of inheritance in\nparticular and reset a given property to its &quot;default&quot; value (in this case,\ninterpreting &quot;default&quot; as including the UA stylesheet).<\/p>\n<p>So I wonder if there would be value in a CSS keyword which actually does that.\nNot to introduce even more confusion into this space, but what if we had a\n(tentatively named) <code>revert-initial<\/code> keyword which is identical to <code>revert<\/code>\nexcept that it just skips the inheritance step:<\/p>\n<blockquote>\n<p><code>revert-initial<\/code> resets the property either to user agent set value, to\nuser set value, <del>to its inherited value (if it is inheritable),<\/del> or to initial\nvalue.<\/p>\n<\/blockquote>\n<p>I&#39;m sure there is a reason for why the spec authors chose to use inheritance\nbefore the <code>initial<\/code> value and likely my use case just isn&#39;t quite what the\noriginal intent of <code>revert<\/code> was.<\/p>\n<p>But <code>revert-initial<\/code> as I&#39;m describing it would eliminate the issue for non-UA\nstyles mentioned above and I think simplify the intent of the feature. Any\ndeveloper who wants to &quot;use the default value after taking the UA stylesheet\ninto account&quot; would likely not expect inheritance to come into play and\n<code>revert-initial<\/code> is probably closer to what they actually want.<\/p>\n<p>I&#39;m still not entirely sure <code>revert-initial<\/code> would be better for this use case\ndue to the issue of\n<a href=\"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/#inherited-properties-from-ua-elements\">inheriting from UA elements<\/a>\nstill being present, but I think it may turn into more of a value judgement call\nrather than a clear technical decision.<\/p>\n<p>But until something like that happens, <code>all: initial;<\/code> is the clear winner\nwhenever you need to isolate CSS inheritance.<\/p>\n<h2 id=\"acknowledgements\">Acknowledgements<\/h2>\n<p><strong>Huge<\/strong> shout out to\n<a href=\"https:\/\/bsky.app\/profile\/jelbourn.bsky.social\" target=\"_blank\">Jeremy Elbourn<\/a> for reviewing\nthis blog post and initially catching that <code>all: revert;<\/code> was the wrong solution\nfor this problem. I definitely could not have figured this all out without his\npatience through several deeply technical conversations on the topic to help me\nunderstand the nuances at play.<\/p>\n<p>Also a big thank you to <a href=\"https:\/\/una.im\/\" target=\"_blank\">Una Kravets<\/a> for clarifying what was\nhappening with <code>color<\/code> and how Chrome manages these properties under the hood.<\/p>\n<h2 id=\"appendix\">Appendix<\/h2>\n<p>A few related topics for your reading pleasure:<\/p>\n<h3 id=\"shadow-dom\">Shadow DOM<\/h3>\n<p>Whenever CSS isolation comes up in conversation, the immediate answer many devs\njump to is\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Web_components\/Using_shadow_DOM\" target=\"_blank\">shadow DOM<\/a>.\nCSS leakage takes several different forms, and shadow DOM is a particularly\nuseful tool for preventing CSS <em>selectors<\/em> from leaking into or out of a\nparticular shadow root. However, it does not prevent CSS <em>inheritance<\/em>, meaning\nit does not apply to this particular problem.<\/p>\n<figure>\n    <figcaption>Example 8: Shadow DOM Inheritance.<\/figcaption>\n\n<aside>\nNote: This demo relies on declarative shadow DOM which\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/HTMLTemplateElement\/shadowRootMode\" target=\"_blank\" rel=\"noopener\">isn't <em>quite<\/em> baseline yet<\/a>,\nso older browsers might not render it correctly.\n<\/aside>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>parent-root<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">color<\/span><span class=\"token punctuation\">:<\/span> red<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    #shadowRoot\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Still red. :(<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    #\/shadowRoot\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div style=\"color: red;\">\n    <template shadowrootmode=\"open\">\n        <div>Still red. :(<\/div>\n    <\/template>\n<\/div><\/figure>\n\n<p>Shadow DOM simply solves a different CSS isolation problem than the one\ndescribed here.<\/p>\n<h3 id=\"scope\"><code>@scope<\/code><\/h3>\n<p>Similar to <a href=\"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/#shadow-dom\">shadow DOM<\/a>,\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/@scope\" target=\"_blank\"><code>@scope<\/code><\/a>\nalso prevents CSS selectors from leaking out of a specific subtree:<\/p>\n<pre><code class=\"language-css\"><span class=\"token atrule\"><span class=\"token rule\">@scope<\/span> <span class=\"token punctuation\">(<\/span>#parent-root<span class=\"token punctuation\">)<\/span> to <span class=\"token punctuation\">(<\/span>#child-root<span class=\"token punctuation\">)<\/span><\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token selector\">div<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token property\">color<\/span><span class=\"token punctuation\">:<\/span> red<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>The above example ensures the <code>div<\/code> selector only matches elements within the\nparent app, but it does nothing to prevent the <code>color: red;<\/code> style from\ninheriting down into the child application.<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/different-problem.avif\" type=\"image\/avif\" width=\"640\" height=\"320\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/isolating-css-inheritance\/different-problem.webp\" alt=\"A meme of an crude MS Paint paint drawing in which a character dressed as a kind of shark (I dunno) who says &quot;No, see, that solution is for a different problem than the one I have.&quot;\" width=\"640\" height=\"320\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<p><code>@scope<\/code> is also not supported in all browsers just yet, but I&#39;m excited to see\nbroader support for it and suspect it will be useful for the wider CSS isolation\nstory once it becomes Baseline.<\/p>\n<h3 id=\"revert-layer\"><code>revert-layer<\/code><\/h3>\n<p>So <code>revert-layer<\/code> is a really unique alternative to <code>initial<\/code> and <code>revert<\/code>. Its\nintended use case to revert the styles only in a specific CSS <code>@layer<\/code>. This\ncould hypothetically be used to revert the styles from a parent application in\nall the child application&#39;s elements.<\/p>\n<p>I won&#39;t go too far into specifics, because I promised myself this would be\nshorter than my average blog post, but you can put each application&#39;s styles\ninto their own <code>@layer<\/code>, and then have the child app container revert the parent\napp&#39;s layer.<\/p>\n<figure>\n    <figcaption>Example 9: <code>@layer<\/code>.<\/figcaption>\n\n<pre><code class=\"language-css\"><span class=\"token atrule\"><span class=\"token rule\">@layer<\/span> parent<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/* Parent application styles... *\/<\/span>\n    <span class=\"token selector\">#parent-root<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token property\">font-weight<\/span><span class=\"token punctuation\">:<\/span> bold<span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token atrule\"><span class=\"token rule\">@layer<\/span> child<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/* Child application styles... *\/<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/* Revert the parent layer on the child root element. *\/<\/span>\n<span class=\"token atrule\"><span class=\"token rule\">@layer<\/span> parent<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token selector\">#child-root<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token property\">font-weight<\/span><span class=\"token punctuation\">:<\/span> revert-layer<span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>parent-root<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>I'm bold!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>child-root<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>I'm still bold?<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div id=\"revert-layer-demo\" class=\"parent-root\">\n    <div>I'm bold!<\/div>\n\n    <div class=\"child-root\">\n        <div>I'm still bold?<\/div>\n    <\/div>\n<\/div><\/figure>\n\n<p>This <em>feels<\/em> like it would work, but actually doesn&#39;t, because <code>revert-layer<\/code>\nonly resets styles for the particular elements matched by its selector. This\nresets the entire property for that element, it does not prevent inheritance for\nan arbitrary descendant.<\/p>\n<p>The correct usage would be:<\/p>\n<pre><code class=\"language-css\"><span class=\"token atrule\"><span class=\"token rule\">@layer<\/span> parent<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/* Revert on the `#parent-root` element. *\/<\/span>\n    <span class=\"token selector\">#parent-root<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token property\">font-weight<\/span><span class=\"token punctuation\">:<\/span> revert-layer<span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>This does revert the style and renders with <code>font-weight: normal;<\/code> as a result,\nhowever this gets applied to the <code>#parent-root<\/code> element, meaning we&#39;ve broken\nthe <code>font-weight<\/code> styling for the <em>parent app<\/em>.<\/p>\n<p>I suppose that&#39;s one way to isolate an application, just break the styling of\nall the other apps on the page so their CSS can never leak into you. \ud83d\ude08<\/p>\n<p>The net result is that you can&#39;t use <code>revert-layer<\/code> as a mechanism to prevent\nCSS inheritance. This is somewhat to be expected really, it reverts layers, not\ninheritance.<\/p>\n<h3 id=\"css-variables\">CSS Variables<\/h3>\n<p><code>all<\/code> applies to all CSS properties (with minor exceptions), but does <em>not<\/em>\napply to CSS variables. As a foundational primitive, it makes sense to support\nresetting all CSS properties while still allowing CSS variables to inherit.\nHowever, for this use case of CSS isolation between multiple apps, preventing\nvariable inheritance is equally as important. The fact that <code>all<\/code> does not apply\nto variables is actually <em>incredibly<\/em> frustrating, as there is no equivalent\nproperty which does. This forces us into an entirely different and much more\ncomplicated solution to isolate CSS variables. One which potentially deserves\nits own blog post, but that&#39;s for another time. Stay focused here, Devel.<\/p>\n<p><a href=\"https:\/\/lea.verou.me\/\" target=\"_blank\">Lea Verou<\/a> has\n<a href=\"https:\/\/lea.verou.me\/blog\/2025\/style-observer\/\" target=\"_blank\">a great post<\/a> on the history of\nobserving CSS variables and the current state-of-the-art solution. But even that\nsolution requires up front knowledge of all the variables you want to observe,\nwhich isn&#39;t really viable for this use case, and isn&#39;t really compatible with\nSSR without a form of DOM emulation.<\/p>\n<p>I really wish there was some kind of <code>all-vars: initial;<\/code> property which would\ndo this. But as of now, the web platform lacks the right primitives to isolate\nCSS variables. \ud83d\ude22<\/p>\n<h3 id=\"the-case-against-user-agent-stylesheets\">The Case Against User-Agent Stylesheets<\/h3>\n<p>Hot take: I&#39;m not convinced user-agent stylesheets are a good idea.<\/p>\n<p>I understand the general goal for UA stylesheets and I&#39;m enough of a proponent\nof the open web to want to support different browsers innovating with different\npresentations, or users customizing their interfaces to fit their personal\npreferences or accessibility needs.<\/p>\n<p>But I struggle to see how these can be practically managed as a web developer.<\/p>\n<p>I mentioned earlier how <code>div { display: block; }<\/code> is actually in the UA\nstylesheet, despite the fact most developers would perceive this as plain\ndefault behavior for <code>div<\/code>. However, as far as I can tell, nothing in the HTML\nstandard actually specifies that <code>div<\/code> <em>must<\/em> be <code>block<\/code>.<\/p>\n<p>This appears as a\n<a href=\"https:\/\/html.spec.whatwg.org\/multipage\/rendering.html#rendering\" target=\"_blank\">\"suggestion\"<\/a>\nin how\n<a href=\"https:\/\/html.spec.whatwg.org\/multipage\/rendering.html#flow-content-3\" target=\"_blank\">flow content should be rendered<\/a>.\nIt\n<a href=\"https:\/\/html.spec.whatwg.org\/multipage\/infrastructure.html#renderingUA\" target=\"_blank\">also says<\/a>\nuser agents &quot;<em>may<\/em> be designated... as supporting the suggested default\nrendering&quot; and that they are &quot;encouraged to offer settings that override this\ndefault&quot;.<\/p>\n<p>Therefore, I believe (spec authors feel free to correct me) that it would\ntechnically be consistent with the spec for a browser to set something like\n<code>div { display: inline-flex; }<\/code> in the UA stylesheet. Imagine how breaking that\nwould be on the entirety of the web! Is there any viable world in which the\nbrowser vendor could argue, &quot;Meh, the fact that all these web pages render\nincorrectly with our innovative <code>inline-flex<\/code> UA stylesheet are bugs in those\npages, they&#39;re relying on the non-standard <code>block<\/code> default.&quot; No one would\nsupport that browser and users would justifiably complain until the vendor\nrelented and switched to <code>block<\/code>.<\/p>\n<p>More realistically, if a vendor creates a new device with its own UX standard\nand tweaks the UA stylesheet to fit their design (think a new platform like\nAndroid or iOS), what guarantee is there that this design will look in any way\nreasonable or even just not visibly break layouts when applied to the vast\nmajority of existing applications with their own custom styling?<\/p>\n<p>When each browser has a different &quot;default stylesheet&quot;, it just makes for\nunreliable default values. Many developers use a\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Reset_style_sheet\" target=\"_blank\">CSS reset<\/a> specifically to\nnormalize these kinds of browser differences into a uniform default state,\neffectively negating the intent behind UA styles in the first place.<\/p>\n<p>I can see a slightly stronger accessibility argument in favor of UA styles,\nwhere users might want to tweak or configure their browser to work better for\nthem, but I&#39;m not convinced this is really the right solution. The web has\nplenty of accessibility hooks from dark theme, to high contrast mode, to\nconfigurable font sizes, with more being added every day. These can be added to\nthe platform without necessarily relying on unpredictable UA stylesheets, though\nI&#39;m certainly no expert and would be interested to hear if there are more\naccessibility use cases with a harder dependency on UA stylesheets than I&#39;m\naware of.<\/p>\n<p>Anyways, thanks for coming to my Ted talk.<\/p>\n"},{"title":"HTML Whitespace is Broken","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/"}},"updated":"2024-09-02T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/","content":"<h1 id=\"html-whitespace-is-broken\">HTML Whitespace is Broken<\/h1>\n<time datetime=\"2024-09-02T19:00:00.000Z\" class=\"timestamp\">September 2, 2024<\/time><p>Recently, I was working on a project which required a deeper understanding of\nhow whitespace works in HTML. I was never a fan of HTML&#39;s whitespace behavior\nbefore as I&#39;ve been burned by it a few times. But as I dug into it more deeply,\nI found myself discovering complex design issues that I wanted to explore in a\nblog post. This is partially to write down my knowledge in this space for future\nreference and partially to vent about how unnecessarily complicated it all is.<\/p>\n<p>So let&#39;s discuss:<\/p>\n<ol>\n<li><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#how-html-whitespace-works\">How whitespace actually works.<\/a><\/li>\n<li><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#how-did-we-get-here\">Why it works that way.<\/a><\/li>\n<li><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#html-tooling\">The problems many HTML tools have.<\/a><\/li>\n<li><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#how-could-we-fix-this\">How it <em>should<\/em> work.<\/a><\/li>\n<li><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#practical-advice\">What we can do about it.<\/a><\/li>\n<\/ol>\n<h2 id=\"how-html-whitespace-works\">How HTML Whitespace Works<\/h2>\n<p><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Document_Object_Model\/Whitespace\" target=\"_blank\">MDN has a great article<\/a>\nexplaining whitespace in HTML but I&#39;ll try to break it down here. Let&#39;s start\nwith <code>inline<\/code> elements.<\/p>\n<h3 id=\"inline-elements\">Inline Elements<\/h3>\n<p>HTML is whitespace-sensitive in that elements will render differently based on\nwhether or not whitespace exists between them. In these two examples, if a space\nis present between the two links, then that space is rendered in the output.<\/p>\n<figure>\n    <figcaption>Example 1: No whitespace.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>First<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Second<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">First<\/a><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">Second<\/a><\/figure>\n\n<figure>\n    <figcaption>Example 2: Single space.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>First<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Second<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">First<\/a> <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">Second<\/a><\/figure>\n\n<p>This makes some amount of sense to me. The difference between 1. and 2. is clear\nin the code, obviously the developer intentionally put a space in 2. and it\nfollows that 1. would not have any space between its links.<\/p>\n<p>Beyond single spaces, HTML is subject to whitespace &quot;collapsing&quot;, where multiple\nspaces are &quot;collapsed&quot; into a single space. This means adding additional spaces\nhas no effect. It&#39;s exactly the same as having one space.<\/p>\n<figure>\n    <figcaption>Example 3: Lots of spaces.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>First<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>       <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Second<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">First<\/a>       <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">Second<\/a><\/figure>\n\n<p>Newlines and tabs are also treated identically and collapsed into spaces.<\/p>\n<figure>\n    <figcaption>Example 4: Newline.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>First<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Second<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">First<\/a>\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">Second<\/a><\/figure>\n\n<p>The space between the tags is rendered as an independent text node, meaning it\ndoes not inherit the styles for either of the <code>&lt;a&gt;<\/code> tags. It does not include an\nunderscore and clicking the whitespace does not trigger either link. Given that\nthe space in HTML is not within either <code>&lt;a&gt;<\/code> tag, that seems pretty reasonable\nto me.<\/p>\n<p>But let&#39;s keep experimenting. If we put this inside a <code>&lt;span&gt;<\/code> tag, then any\nleading and trailing whitespace is <em>not<\/em> preserved.<\/p>\n<figure>\n    <figcaption>Example 5: Indented.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>First<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Second<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><span>\n            <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">First<\/a>\n            <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">Second<\/a>\n<\/span><\/figure>\n\n<p>Even though there are many spaces before the first <code>&lt;a&gt;<\/code>, they do not render to\nthe user. This is because whitespace at the start of a rendering context\n(basically whitespace before the first line of a block) is removed completely.<\/p>\n<p>Typically, spaces which are visible to the user are referred to as\n<em>significant<\/em>, while spaces which are not rendered are considered\n<em>insignificant<\/em>. For the above example, the newline and indentation between the\nlinks are significant because they will be collapsed to a single space and\nrendered. The indentation before the first link and trailing newline after the\nsecond link are insignificant and not displayed to the user.<\/p>\n<p>This also applies to whitespace inside a tag. Consider these examples:<\/p>\n<figure>\n    <figcaption>Example 6: Basic link.<\/figcaption>\n\n<pre><code class=\"language-html\">Hello, <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>World<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>!\n<\/code><\/pre>Hello, <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">World<\/a>!<\/figure>\n\n<figure>\n    <figcaption>Example 7: Spaced link.<\/figcaption>\n\n<pre><code class=\"language-html\">Hello, <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span> World <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>!\n<\/code><\/pre>Hello, <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\"> World <\/a>!<\/figure>\n\n<figure>\n    <figcaption>Example 8. Very spacey link.<\/figcaption>\n\n<pre><code class=\"language-html\">Hello, <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>        World          <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>!\n<\/code><\/pre>Hello, <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">        World          <\/a>!<\/figure>\n\n<p>In 7., we can see that the space between &quot;World&quot; and &quot;!&quot; is preserved and the\nspace is underscored with the rest of the link. If you click that space\nprecisely enough you&#39;ll actually follow the link.<\/p>\n<p>In fact 7., shows even more collapsing. There are actually <em>two<\/em> spaces between\n&quot;Hello,&quot; and &quot;World&quot;, one outside the <code>&lt;a&gt;<\/code> tag and the other inside it. You\nmight expect this to render two spaces, the latter of which is underlined\nbecause it is a part of the link.<\/p>\n<p>However the browser actually collapses both spaces together and only displays\none. The begs the question: Which space is preserved? How does the browser\ndecide?<\/p>\n<p>Let&#39;s test this out by swapping the ordering:<\/p>\n<figure>\n    <figcaption>Example 9: Link before text.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello, <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span> World!\n<\/code><\/pre><a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">Hello, <\/a> World!<\/figure>\n\n<p>Here we see that the space <em>is<\/em> underscored, so the space was again given to the\npreceding text node.<\/p>\n<p>This also highlights the most common foot gun I&#39;ve seen with HTML whitespace:\nlinks with extra spaces. Consider this example:<\/p>\n<figure>\n    <figcaption>Example 10: Long link text.<\/figcaption>\n\n<pre><code class=\"language-html\">Hello, <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    here is some long link text that goes on its own line\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span> please take a look at it!\n<\/code><\/pre>Hello, <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">\n    here is some long link text that goes on its own line\n<\/a> please take a look at it!<\/figure>\n\n<p>Since the link is on its own line, the text ends with a newline character before\nthe <code>&lt;\/a&gt;<\/code>. This means the rendered output places the space within the link\nitself, so the underscore trails one character further than you might expect.<\/p>\n<p>There&#39;s also a space after the <code>&lt;\/a&gt;<\/code>, meaning this falls into the case where\nthere are multiple spaces across two elements. As a result, the space goes to\nthe preceding node which is the link in this case. The solution here is to\nremove the newline at the end of the <code>&lt;a&gt;<\/code> tag by reformatting it, line length\nlimits be dammed.<\/p>\n<figure>\n    <figcaption>Example 11: Single-line link.<\/figcaption>\n\n<pre><code class=\"language-html\">Hello,\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>here is some long link text that goes on its own line<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\nplease take a look at it!\n<\/code><\/pre>Hello,\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">here is some long link text that goes on its own line<\/a>\nplease take a look at it!<\/figure>\n\n<p>Your formatter might not like this solution, but we&#39;ll\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#automated-formatting\">get to that later<\/a>.<\/p>\n<h3 id=\"block-elements\">Block Elements<\/h3>\n<p>All of the above applies to <em>inline<\/em> HTML elements.<\/p>\n<p><em>Block<\/em> elements are similar, but preserve a little less whitespace. As\nmentioned earlier about inline elements, any spaces at the start or end of a\nline are dropped. Block elements work similarly. Any whitespace in a\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/CSS_display\/Block_formatting_context\" target=\"_blank\">block formatting context<\/a>\nbecomes its own block, except that whitespace-only blocks are then dropped\nentirely. Practically speaking, this means that any spaces around blocks are\neffectively ignored.<\/p>\n<figure>\n    <figcaption>Example 12: Block elements without whitespace.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Hello<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>World<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div>Hello<\/div><div>World<\/div><\/figure>\n\n<figure>\n    <figcaption>Example 13: Block elements with whitespace.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Hello<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>      <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>World<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div>Hello<\/div>      <div>World<\/div><\/figure>\n\n<figure>\n    <figcaption>Example 14: Block elements with newline.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Hello<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>World<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div>Hello<\/div>\n<div>World<\/div><\/figure>\n\n<p>Recall that for inline elements, a space between them is significant and gets\nincluded in the former element.<\/p>\n<p>For block elements, there&#39;s actually no difference between these examples\nbecause all the whitespace differences are ignored and newlines are placed\nbetween the blocks. Example 12. does not actually contain <em>any<\/em> whitespace, yet\nthe two <code>&lt;div&gt;<\/code> tags are presented as if there is a newline between them.<\/p>\n<h3 id=\"css\">CSS<\/h3>\n<p>Now that you understand how block and inline elements behave, let&#39;s do a quick\npop quiz, how do you expect the following to render?<\/p>\n<figure>\n    <figcaption>Example 15: <code>&lt;aside&gt;<\/code> without whitespace.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>Hello<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>World<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><\/figure>\n\n<p>You might intuitively think, &quot;Well <code>&lt;aside&gt;<\/code> is a block element, so it should\nfollow the same rules as <code>&lt;div&gt;<\/code>. Therefore this will render exactly like\nexample 12., and there&#39;s a newline between them.&quot;<\/p>\n<p>That&#39;s very well-reasoned of you, and you are correct... <em>most<\/em> of the time...\nThis is actually a trick question. <code>&lt;aside&gt;<\/code> is natively a block element, but it\ndoesn&#39;t have to be. Therefore you can actually render different spacing based on\nhow you <em>style<\/em> the element.<\/p>\n<figure>\n    <figcaption>Example 16: Block <code>&lt;aside&gt;<\/code>.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>style<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token style\"><span class=\"token language-css\"><span class=\"token selector\">aside<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> <span class=\"token string\">'block'<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token punctuation\">}<\/span><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>style<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>Hello<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>World<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><aside>Hello<\/aside><aside>World<\/aside><\/figure>\n\n<figure>\n    <figcaption>Example 17: Inline <code>&lt;aside&gt;<\/code>.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>style<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token style\"><span class=\"token language-css\"><span class=\"token selector\">aside<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> <span class=\"token string\">'inline'<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token punctuation\">}<\/span><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>style<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>Hello<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>World<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><aside style=\"display: inline;\">Hello<\/aside><aside style=\"display: inline;\">World<\/aside><\/figure>\n\n<p>The same HTML can actually lead to different whitespace behavior. That might not\nsound too bad. After all, this is exactly the layout difference between <code>block<\/code>\nand <code>inline<\/code>. However it actually <em>changes<\/em> the fundamental text content\ndisplayed to the user. Example 16. displays two strings, &quot;Hello&quot; and &quot;World&quot;.\nWhile 17. displays a single string &quot;HelloWorld&quot;. There&#39;s a semantic difference\nbetween those two options, not just a styling distinction.<\/p>\n<p>You can actually observe this distinction in JavaScript through\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Node\/textContent\" target=\"_blank\"><code>textContent<\/code><\/a>\nand\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/HTMLElement\/innerText\" target=\"_blank\"><code>innerText<\/code><\/a>\non a parent element. The former joins the strings together with no spacing in\nboth cases.<\/p>\n<pre><code>&gt; parentOfBlockAsides.textContent\n&#39;HelloWorld&#39;\n&gt; parentOfInlineAsides.textContent\n&#39;HelloWorld&#39;\n<\/code><\/pre><p>However <code>innerText<\/code> adds a newline for the <code>block<\/code> elements <em>only<\/em>:<\/p>\n<pre><code>&gt; parentOfBlockAsides.innerText\n&#39;Hello\\nWorld&#39;\n&gt; parentOfInlineAsides.innerText\n&#39;HelloWorld&#39;\n<\/code><\/pre><p><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Node\/textContent#differences_from_innertext\" target=\"_blank\">Per MDN<\/a>,\n<code>innerText<\/code> is &quot;aware of styling&quot; so it can tell the difference between these\ntwo examples in a way <code>textContent<\/code> cannot.<\/p>\n<p>You can even hear the difference with text-to-speech tools! Windows Narrator on\nChrome treats block elements as different text fields while inline elements are\njoined into a single word.<\/p>\n<p>Here I put the word &quot;Refrigerator&quot; split across multiple <code>&lt;aside&gt;<\/code> tags. The\nfirst attempt uses the default <code>display: block;<\/code> while the second is\n<code>display: inline;<\/code>.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/demos\/1-refrigerator.mp4\" type=\"video\/mp4\" \/>\n\n                    <track label=\"English\" kind=\"subtitles\" srclang=\"en\" src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/demos\/1-refrigerator.vtt\" default=\"\" \/>\n\n        <\/video>\n<\/template>\n    <noscript>        <video loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/demos\/1-refrigerator.mp4\" type=\"video\/mp4\" \/>\n\n                    <track label=\"English\" kind=\"subtitles\" srclang=\"en\" src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/demos\/1-refrigerator.vtt\" default=\"\" \/>\n\n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>Narrator treats the first attempt as four different words. It implicitly\nconverts &quot;fri&quot; to &quot;Friday&quot; (assuming certain semantics on the text) and can&#39;t\npronounce &quot;ger&quot; at all, choosing to spell it out instead as &quot;g-e-r&quot;.<\/p>\n<p>The second attempt correctly speaks &quot;Refrigerator&quot; even though it has identical\nDOM structure to the first attempt. The only difference is the <code>display<\/code>\nproperty. This tells us two things:<\/p>\n<p>First, whitespace handling of HTML content can be controlled purely through CSS.\nThis is also interesting because it means that whitespace handling is not done\nby the HTML parser. The parser must retain all spaces because it&#39;s actually the\nCSS layer which decides whether or not those spaces are significant.<\/p>\n<p>Second, the actual <em>content<\/em> of a web page can be manipulated by CSS. The page\nshould contain either &quot;Refrigerator&quot; or &quot;Re-fri-ger-ator&quot;, regardless of the CSS\napplied. The presentation layer of CSS should not get to decide which of those\ntwo interpretations is correct, that&#39;s HTML&#39;s job. This also implies that search\nengines may index different textual content based whether they process a page&#39;s\nCSS styling, which really bulldozes any idea of separation of concerns between\nHTML and CSS.<\/p>\n<h3 id=\"preformatted-text\">Preformatted Text<\/h3>\n<p>&quot;But wait!&quot; I hear you say. &quot;If you don&#39;t like HTML spacing, just use the\n<code>&lt;pre&gt;<\/code> tag!&quot;<\/p>\n<p>Yes, that is a valid point. HTML does have a <code>&lt;pre&gt;<\/code> tag for &quot;preformatted&quot; text\nwhich automatically preserves <em>all<\/em> whitespace.<\/p>\n<figure>\n    <figcaption>Example 18: Preformatted text.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\nHello world\nI am preformatted         text, which is interesting.\n    This line is indented more than the rest!\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><pre>\nHello world\nI am preformatted         text, which is interesting.\n    This line is indented more than the rest!\n<\/pre><\/figure>\n\n<p>No whitespace collapsing occurs and all of it is considered significant...\nexcept when it isn&#39;t, thanks HTML! There are actually two insignificant spaces\nhere:<\/p>\n<ol>\n<li>The first newline immediately following the initial <code>&lt;pre&gt;<\/code>\n(<code>&lt;pre&gt;\\nHello...<\/code>).<\/li>\n<li>The last newline immediately preceding the final <code>&lt;\/pre&gt;<\/code>\n(<code>than the rest!\\n&lt;\/pre&gt;<\/code>).<\/li>\n<\/ol>\n<p>Neither of these newlines are rendered. There&#39;s no blank line at the start or\nend of the rendered result. Surprisingly, if we check <code>textContent<\/code> we don&#39;t see\nthe first newline, but we <em>do<\/em> see the second newline, even though it&#39;s not\nrendered.<\/p>\n<pre><code>&gt; preElement.textContent\n&#39;Hello world\\n...than the rest!\\n&#39;\n<\/code><\/pre><p>This detail hints at even more nuanced behavior, as whitespace at the start of a\n<code>&lt;pre&gt;<\/code> tag is treated <em>differently<\/em> from whitespace at the end.<\/p>\n<figure>\n    <figcaption>\n        Example 19: Preformatted text with leading \/ trailing whitespace.\n    <\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n\nHello world\n\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><pre>\n\nHello world\n\n<\/pre><\/figure>\n\n<p>Writing this out directly, the source text looks like:<\/p>\n<pre><code>\\n\\nHello world\\n\\n\n<\/code><\/pre><p>Here, you&#39;ll notice the two newline characters at the start are dropped and not\nrendered at all. However, only one newline character at the end is dropped, and\nwe end up rendering an extra line. So all newlines at the start of a <code>&lt;pre&gt;<\/code> tag\nare dropped, but only the <em>last<\/em> newline at the end is dropped.<\/p>\n<p>If we add spaces between the <code>&lt;pre&gt;<\/code> and <code>&lt;\/pre&gt;<\/code> tags and their nearest\nnewlines... (I&#39;m using an underscore to make this visible).<\/p>\n<figure>\n    <figcaption>\n        Example 20: Preformatted text with leading\/trailing spaces.\n    <\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>_\nHello world\n_<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><!-- Using `&#32;` here so the spaces don't get removed by the formatter. -->\n\n<pre>&#32;\nHello world\n&#32;<\/pre><\/figure>\n\n<p>Now we get the empty lines at the start and end of the block. This means\n<code>&lt;pre&gt;<\/code> tags treat newlines distinctly from other spaces, and those newlines\n<em>must<\/em> be the first or last characters of the text.<\/p>\n<p>I can kind of see where the spec authors were going here. Usually if you&#39;re\nputting a <code>&lt;pre&gt;<\/code> tag on the page, you&#39;re probably going to put a newline before\nthe content like so:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\nSome preformatted text\nwhich is multiple lines.\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>You&#39;re probably not going to do:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>Some preformatted text\nwhich is multiple lines.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>even though that would be more accurate when it comes to whitespace handling.\nThe main takeaway is that even <code>&lt;pre&gt;<\/code> isn&#39;t as straightforward as you might\nhave expected, despite that being kind of the whole point of the tag. Not only\nthat, but up until now spaces and newlines have used the same collapsing\nbehavior. This shows us that newlines and spaces can sometimes be treated\ndistinctly from each other.<\/p>\n<p><strong>Addendum:<\/strong> Several readers have pointed out that the behavior for <code>&lt;pre&gt;<\/code> to\ncollapse leading and trailing newlines is actually implemented by the\n<a href=\"https:\/\/html.spec.whatwg.org\/multipage\/parsing.html#parsing-main-inbody\" target=\"_blank\">HTML parser<\/a>,\nnot CSS. This makes it even more fun because <code>white-space: pre;<\/code>\n(<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#white-space\">discussed later<\/a>) does <em>not<\/em> apply the same behavior. This\nmeans <code>&lt;pre&gt;<\/code> and <code>&lt;div style=&quot;white-space: pre;&quot;&gt;<\/code> actually differ in this\nrespect.<\/p>\n<p><code>&lt;pre&gt;<\/code> is also just generally unergonomic. While the whitespace behavior is\ndefinitely more intuitive, you can&#39;t indent it at all without affecting its\ncontent. Compare these two examples:<\/p>\n<figure>\n    <figcaption>Example 21: Indented <code>&lt;pre&gt;<\/code> tag.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n    Hello, World!\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><pre>\n    Hello, World!\n<\/pre><\/figure>\n\n<figure>\n    <figcaption>\n        Example 22: Double indented <code>&lt;pre&gt;<\/code> tag.\n    <\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n        Hello, World!\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div>\n    <pre>\n        Hello, World!\n    <\/pre>\n<\/div><\/figure>\n\n<p>These both feel like they should contain the same text &quot;Hello, World!&quot; and\nthat&#39;s clearly the developer&#39;s intent. However 21. is preceded by 4 spaces while\n22. is preceded by 8 spaces and trailed with a newline and another 4 spaces.\nThis is especially tricky because the indentation causes spaces to come <em>after<\/em>\nthe trailing newline, so the <code>&lt;\/pre&gt;<\/code> collapsing of a final newline doesn&#39;t\napply because it&#39;s not the last character. Therefore, we end up with an extra\nblank line in the output.<\/p>\n<p>One other challenge is that <code>&lt;pre&gt;<\/code> applies its whitespace rules to the entire\nelement, which can be much broader than really necessary. Like the links with\ntrailing spaces earlier, sometimes the problem is just a single space. If you\nfix that problem by using a <code>&lt;pre&gt;<\/code> tag, you&#39;re likely just creating more\nproblems for all the other spaces in the text which were previously rendering\njust fine.<\/p>\n<p>So while <code>&lt;pre&gt;<\/code> does solve a number of whitespace issues I&#39;ve described, it\ncauses a whole separate set of developer experience (DX) issues which make it\nharder and less ergonomic to use correctly.<\/p>\n<h3 id=\"white-space\"><code>white-space<\/code><\/h3>\n<p><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/white-space\" target=\"_blank\">The <code>white-space<\/code> CSS property<\/a>\nadds even more complexity to this. It supports <code>white-space: pre;<\/code> which can\nbasically opt any element into the <code>&lt;pre&gt;<\/code> tag&#39;s parsing rules. It also supports\n<code>pre-line<\/code>, <code>pre-wrap<\/code> and a few other possible options to further configure the\nbehavior for specific use cases.<\/p>\n<p>As I mentioned earlier, whitespace processing is defined by CSS rules, not the\nHTML parser so the\n<a href=\"https:\/\/drafts.csswg.org\/css-text\/\" target=\"_blank\">standard which specifies this behavior<\/a> is\nactually maintained by the CSS working group and primarily focuses on the\nbehavior of the <code>white-space<\/code> property.<\/p>\n<p>Between block elements, inline elements, and <code>&lt;pre&gt;<\/code> tags I think I&#39;ve done a\ndecent job justifying why HTML whitespace is confusing. However if you still\ndon&#39;t believe me, I&#39;ll also mention that flexbox\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#whitespace-of-flexbox-elements\">forces block rendering on its children<\/a> and\n<code>inline-block<\/code> elements are also\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#whitespace-of-inline-block-elements\">sensitive to minor whitespace changes<\/a>.<\/p>\n<h3 id=\"nbsp\"><code>&amp;nbsp;<\/code><\/h3>\n<p>So if this is all so complicated and <code>&lt;pre&gt;<\/code> isn&#39;t the right solution, what\nother options are there?<\/p>\n<p>We&#39;ve all been there. Two elements are right next to each other and you need\njust a little spacing between them. What do you do? <code>&amp;nbsp;<\/code><\/p>\n<p>If you&#39;ve never understood what this actually is, <code>&amp;nbsp;<\/code> is an\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Glossary\/Entity\" target=\"_blank\">HTML entity<\/a>\nrepresenting a <a href=\"https:\/\/unicode-explorer.com\/c\/00A0\" target=\"_blank\">\"no-break space\"<\/a>.\nSpecifically, it&#39;s a space which the browser will never line wrap on.\n<code>Hello&amp;nbsp;World<\/code> will never be split up into <code>Hello<\/code> and <code>World<\/code> on different\nlines, no matter how narrow the viewport gets.<\/p>\n<p>This is a useful, but frequently misused tool. If you need a space between two\nelements, especially elements in an inline text context where devs frequently\nreach for <code>&amp;nbsp;<\/code>, you probably don&#39;t want the non-breaking behavior. If the\nentity appears outside of a text context, such as between two blocks, then the\nnon-breaking behavior doesn&#39;t even apply and has no effect.<\/p>\n<p>Instead, I suspect what devs really <em>want<\/em> from <code>&amp;nbsp;<\/code> is its non-collapsible\nbehavior. Multiple <code>&amp;nbsp;<\/code> characters are not merged together and they can\nstart or end lines.<\/p>\n<figure>\n    <figcaption>\n        Example 23: <code>&amp;nbsp;<\/code>.\n    <\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Hello,<span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span><span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span><span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span><span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span><span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span>World<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span><span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span><span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span><span class=\"token entity named-entity\" title=\"&nbsp;\">&amp;nbsp;<\/span>test<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div>Hello,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;World<\/div>\n<div>&nbsp;<\/div>\n<div>&nbsp;&nbsp;&nbsp;&nbsp;test<\/div><\/figure>\n\n<p><code>&amp;nbsp;<\/code> is not considered whitespace like newlines, tabs, or general spaces so\ncollapsing rules treat it like any other text.<\/p>\n<p>This sounds nice but comes with additional baggage. Beyond the non-breaking\nbehavior, <code>&amp;nbsp;<\/code> <em>always<\/em> takes up exactly one space-worth of width and this\nis never reduced. Except there is one extremely common scenario where spaces are\neliminated, and that&#39;s line wrapping.<\/p>\n<p><code>&amp;nbsp;<\/code> is a non-breaking space, so you&#39;d think it never line wraps. Except as\nI mentioned, the &quot;non-breaking&quot; behavior has no effect when used outside of a\ntext context. So if you use <code>&amp;nbsp;<\/code> to space out two blocks, you&#39;ve created a\nline wrapping problem. Check out this example of two red boxes with a blue\n<code>&amp;nbsp;<\/code> between them:<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/demos\/3-nbsp-overflow.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/demos\/3-nbsp-overflow.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>The ideal behavior would only show the space between the two squares when they\nare adjacent to each other, but <code>&amp;nbsp;<\/code> is not able to support that and\n<em>always<\/em> takes up space, even if the boxes are already separated due to line\nwrapping. I suspect most usages of <code>&amp;nbsp;<\/code> actually have line wrapping bugs\nwhich developers don&#39;t notice because they don&#39;t go out of their way to test\nthis particular behavior.<\/p>\n<p>Unfortunately there&#39;s no great alternative to <code>&amp;nbsp;<\/code> which would line wrap in\nthe correct fashion. <code>&amp;#32;<\/code> sounds like the right entity, but that\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#32\">gets collapsed<\/a> like a regular space, so it doesn&#39;t help here either.<\/p>\n<p>So what&#39;s the correct solution for spacing out two elements? Well it&#39;s probably\nbest to do this in CSS with <code>margin<\/code>, <code>padding<\/code>, or any of the other thousand\nproperties which introduce spacing and fail to center elements. If you really\nneed to, a <code>&lt;pre&gt;<\/code> tag or the <code>white-space<\/code> property is probably the best way to\nhave maximum control over your spacing behavior. However, I honestly can&#39;t blame\nyou if you still end up reaching for <code>&amp;nbsp;<\/code>. I don&#39;t have a great alternative\nbeyond &quot;do it in CSS&quot;, which just isn&#39;t a drop-in solution.<\/p>\n<h2 id=\"how-did-we-get-here\">How Did We Get Here?<\/h2>\n<p>Why exactly does HTML work this way? Why did we make this language so\ncomplicated?<\/p>\n<p>I think the core problem here is that all whitespace in HTML is <em>ambiguous<\/em>.\nSpecifically, it is ambiguous with regard to the developer&#39;s intent. For any\ngiven space, did the developer mean for it to be displayed to the user or did\nthey just want to keep their code under the line length limit? It&#39;s impossible\nfor the browser to know.<\/p>\n<p>To address this, the designers of HTML tried to come up with a set of rules\nwhich would roughly map the HTML code they wanted to write to the rendered\noutput they wanted to create. So you, as a developer, have a UI in your head and\nwrite out the HTML to display it, and usually the whitespace &quot;just works&quot;.\nHonestly, I&#39;m kind of amazed the browser is as consistently correct as it is.<\/p>\n<p>But even that isn&#39;t 100% correct. Sometimes the developer doesn&#39;t expect\nwhitespace to behave the way it does and leads to complicated, hard to\nunderstand bugs. <code>&lt;pre&gt;<\/code> tags simplify things and are intended for use cases\nwhere whitespace is significant and needs to be retained, but it makes authoring\nthose strings in HTML really awkward and overly precise.<\/p>\n<p>Developers are forced to choose between the default syntax that <em>usually<\/em> works\nand is convenient to write or a <code>&lt;pre&gt;<\/code> syntax which can very precisely express\nthe spacing they want but is incredibly awkward and inconvenient to work with.<\/p>\n<p>Contrast this with basically any other programming language where user visible\nstrings are syntactically distinct from general whitespace:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">function<\/span> <span class=\"token function\">sayHello<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token string\">'Hello, World!'<\/span> <span class=\"token operator\">+<\/span>\n        <span class=\"token string\">' I\\'m some text without a newline.'<\/span> <span class=\"token operator\">+<\/span>\n        <span class=\"token string\">' and I\\'m some text with a trailing newline.\\n'<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>All the spaces and newlines are explicit. Everything within the quotes is\nintended for the end-user and everything outside the quotes is intended for the\ndeveloper. This format has its own problems, multiline text can get very awkward\nfor example. But it&#39;s at least unambiguous whether any given space is\nsignificant to the end user or insignificant and intended only for the\ndeveloper.<\/p>\n<p>Just imagine working in a language where text didn&#39;t need to be quoted:<\/p>\n<pre><code>function sayHello(): string {\n    return Hello, World! +\n         I&#39;m some text without a newline. +\n         and I&#39;m some text with a trailing newline.\\n;\n}\n<\/code><\/pre><p>That sounds awful and I have no idea how it would work. Except you don&#39;t need to\nimagine such a situation, because you already write HTML which works exactly\nlike this, and despite writing a whole blog post on the matter, I have no idea\nhow that works either!<\/p>\n<p>Also, if you believe HTML&#39;s syntax is justified because it is intended to\nrepresent documents and occasionally authored by non-developers, I just want to\nsay: <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#isnt-html-just-a-document\">No it isn't.<\/a><\/p>\n<h2 id=\"html-tooling\">HTML Tooling<\/h2>\n<p>Let&#39;s zoom out from the browser to talk about the developer writing HTML and the\ntools which help them succeed. Any tool which processes HTML needs to understand\nthese whitespace semantics, so let&#39;s look at just three:\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#automated-formatting\">automated formatting<\/a>,\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#content-management-systems\">Content Management Systems<\/a>, and\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#minification\">minification<\/a>.<\/p>\n<h3 id=\"automated-formatting\">Automated Formatting<\/h3>\n<p>For as long as we&#39;ve had code, we&#39;ve had arguments about the best way to write\nit. Everyone&#39;s got an opinion and all of them except mine are wrong. So we use\ntools which automatically format everyone&#39;s code into a single, consistent,\nagreed-upon format. Sounds great.<\/p>\n<p>The problem with this is that formatting regularly changes whitespace. A long\nelement can be broken up into multiple lines:<\/p>\n<pre><code class=\"language-html\"><span class=\"token comment\">&lt;!-- Before --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">class<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>cool colorful bright awesome<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Here is some long text.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token comment\">&lt;!-- After --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">class<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>cool colorful bright awesome<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    Here is some long text.\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Anything affecting indenting can also cause line breaks. For example,\nconsider adding a wrapper <code>&lt;div&gt;<\/code>.<\/p>\n<pre><code class=\"language-html\"><span class=\"token comment\">&lt;!-- Before --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Here is some long text saying important stuff.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token comment\">&lt;!-- After --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">class<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>wrapper<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token comment\">&lt;!-- Now it's over the length limit and gets wrapped! --><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n        Here is some long text saying important stuff.\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>These formatting changes are intended to be no-ops. They make my life easier as\na developer, but should never change significant whitespace for the user. Except\nthey do change significant whitespace because they introduce leading and\ntrailing spaces. Consider:<\/p>\n<figure>\n    <figcaption>Example 24. One-line link.<\/figcaption>\n\n<pre><code class=\"language-html\">Check out my <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>web site<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span> and read my blog!\n<\/code><\/pre>Check out my <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">web site<\/a> and read my blog!<\/figure>\n\n<p>In this case we have text with a link in the middle. But if this exceeds the\nline length limit, formatting the text can introduce line breaks like:<\/p>\n<figure>\n    <figcaption>25. Link with overextended underline.<\/figcaption>\n\n<pre><code class=\"language-html\">Check out my\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    web site\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\nand read my blog!\n<\/code><\/pre>Check out my\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#\">\n    web site\n<\/a>\nand read my blog!<\/figure>\n\n<p>Now we have that overextended underline again, all because of a single\nformatting change!<\/p>\n<p><a href=\"https:\/\/prettier.io\/\" target=\"_blank\">Prettier<\/a> actually has an option for this called\n<a href=\"https:\/\/prettier.io\/docs\/en\/options.html#html-whitespace-sensitivity\" target=\"_blank\"><code>--html-whitespace-sensitivity<\/code><\/a>.\nSetting this to <code>ignore<\/code> will allow the above change, so the formatted code\nlooks great, but may break your UI. <code>strict<\/code> will avoid introducing a\nsignificant whitespace change so your UI is safe, but leads to truly &quot;pretty&quot;\nHTML code like:<\/p>\n<pre><code class=\"language-html\">Check out my\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span>\n  <span class=\"token punctuation\">><\/span><\/span>web site<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span>\n<span class=\"token punctuation\">><\/span><\/span>\nand read my blog!\n<\/code><\/pre><p>In strict mode, Prettier can&#39;t introduce a newline between <code>&lt;a&gt;<\/code> and <code>web<\/code>\nbecause that could change the rendered output. Instead, it has to put the\nnewline <em>inside<\/em> the <code>&lt;a&gt;<\/code> start tag since that&#39;s the only location it can add\ninsignificant whitespace. Same for the <code>&lt;\/a&gt;<\/code> and the following <code>and<\/code>.<\/p>\n<p>Prettier also has an <code>--html-whitespace-sensitivity css<\/code> option which tells it\nto &quot;Respect the default value of CSS <code>display<\/code> property.&quot; Hopefully after\nreading this post you should know what that means! Given a <code>&lt;div&gt;<\/code> tag, it can\nformat with the <code>ignore<\/code> behavior because leading and trailing whitespace aren&#39;t\nsignificant in block rendering contexts. <code>&lt;span&gt;<\/code> tags will use <code>strict<\/code>\nbehavior because the leading and trailing whitespace <em>is<\/em> significant. This\nmakes a lot of sense as a useful middle ground between <code>ignore<\/code> and <code>strict<\/code>.<\/p>\n<p>But after reading this post you should also know that&#39;s not entirely accurate\nand breaks if you do <code>div { display: inline; }<\/code>. Prettier doesn&#39;t know anything\nabout your CSS so it can only infer the default <code>display<\/code> for a given tag, it\ncan&#39;t know the actual <code>display<\/code> value used at runtime.<\/p>\n<p>No shame on Prettier here by the way. I can&#39;t blame the tool for formatting HTML\nlike this. The <code>css<\/code> mode is actually a very useful middle ground for getting\nthe nicer <code>ignore<\/code> formatting in at least most of the cases where it won&#39;t have\nany negative effects while still using <code>strict<\/code> where it&#39;s likely to be\nimportant.<\/p>\n<p>Again, the real problem here is that HTML whitespace is ambiguous and can&#39;t tell\nthat Prettier wants to insert whitespace for the developer&#39;s benefit without\naffecting the rendered output. The fact that you can&#39;t know the actual\nwhitespace behavior without knowing the CSS <code>display<\/code> and <code>white-space<\/code>\nproperties is just the cherry on top that cements HTML formatting as a\nfundamentally unsolvable problem.<\/p>\n<h3 id=\"content-management-systems\">Content Management Systems<\/h3>\n<p>Many hands are involved in developing and shipping a web page from scratch to\nits end users. Web developers, designers, product managers, and so much more\nparticipate in various parts of the process. As a result, the idea of a single\nindividual writing an entire web page from scratch in a <code>*.html<\/code> file is\nrelatively rare in the year 2024.<\/p>\n<p>A very common scenario is for a web developer to focus on the &quot;HTML parts&quot; of\nthe page while the marketing, product, or localization teams are focused on the\nraw text content inside a separate content management system (CMS). An\ne-commerce site selling shoes probably does not want to file a bug with the\ndevelopers every time they need to update the marketing copy for how the shoes\nwill make you a faster runner in a not-at-all-legally-binding manner. As a\nresult, modern HTML code looks less like <code>&lt;span&gt;Fast shoes.&lt;\/span&gt;<\/code> and more\nlike:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>${cms.getString('shoes.description')}<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>That sounds straightforward, but pulls on a whole host of whitespace issues. The\ncontent is displayed in an HTML context, meaning HTML&#39;s whitespace rules still\napply, however the author of the text likely doesn&#39;t know that.<\/p>\n<p>For example, if the text starts or ends with whitespace, that whitespace will be\nnaturally placed into the <code>&lt;span&gt;<\/code> and affect spacing with adjacent elements.<\/p>\n<p>Another possibility is if the marketing team is led by one of those people who\ninsists on all sentences ending with two spaces after the period. Those two\nspaces will be collapsed into a single space, and lead to a very upset marketing\nteam which directly leads to a mildly annoyed development team.<\/p>\n<p>Those use cases are possible, but not exactly common and likely something most\ndevelopers can just ignore. However you have to imagine that the marketing team\nis looking at a text field like this:<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/shoes-description.webp\" type=\"image\/webp\" width=\"624\" height=\"144\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/shoes-description.png\" alt=\"Screenshot of a text area labeled &quot;Description&quot;. The user has entered &quot;These shoes will make you the fastest* runner around!&quot; This is followed by two newlines and then a disclaimer &quot;* Not legally binding.&quot;\" width=\"624\" height=\"144\" decoding=\"async\" loading=\"eager\" fetchpriority=\"high\" \/>\n<\/picture><\/p>\n<p>Marketing is interpreting the content as plain text, but that&#39;s\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#isnt-html-just-a-document\">not how HTML works<\/a>. As a result, they end up\nlooking at a completely borked disclaimer:<\/p>\n<blockquote>\nThese shoes will make you\nthe fastest* runner around!\n\n* Not legally binding.<\/blockquote>\n<p>You&#39;d think the CMS should be able to solve this problem, but it really can&#39;t.\nThere&#39;s two newlines between <code>around!<\/code> and <code>* Not<\/code>, but there&#39;s no trivial\nreplacement which will prevent them from being collapsed into a single space.\nThe only viable option here is to render all text as <code>&lt;pre&gt;<\/code>, which is a very\nheavy-handed solution and forces <em>all<\/em> whitespace to be retained when likely\nonly some of it actually mattered. For example, the newline between <code>you<\/code> and\n<code>the<\/code> is likely just the author avoiding a horizontal scrollbar in the text\narea, not a hard line break which end users should see. Realistically, both the\nCMS and the individual writing this copy need some understanding of HTML&#39;s\nwhitespace collapsing rules which will be applied to it.<\/p>\n<p>One other negative effect is that it becomes difficult to reuse text content\nbetween multiple frontends. For example, if the same shoes are displayed in a\nnative Android or iOS app which don&#39;t have the same whitespace collapsing\nbehavior, they will render the same text differently. This makes it very\ndifficult to ensure that the same text is actually rendered consistently and\nimplicitly couples any text rendered to HTML to the whitespace collapsing rules\nof that environment, even though the raw text itself should be independently\nusable in any frontend.<\/p>\n<h3 id=\"minification\">Minification<\/h3>\n<p>The same problems exist for HTML minifiers: tools which remove unnecessary\ncontent from web pages to reduce file size. Multiple spaces are equivalent to\nsingle spaces, so they can pretty easily reduce<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    Hello       World\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>down to just<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span> Hello World <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>But they need to retain those leading and trailing spaces for all the same\nreasons as mentioned above. HTML minifiers can&#39;t know for certain what elements\nwill render in which kind of context and exactly what the whitespace behavior\nwill be. Therefore they need to retain a bunch of spaces which likely don&#39;t\nmatter to make sure they retain the one space which does matter and accept a\nlarger output file size, penalizing all users of the page.<\/p>\n<p><strong>Addendum:<\/strong> After publishing this blog post I came to realize that\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#whitespace-of-inline-block-elements\">example 31<\/a> was broken in production\nbecause my blog&#39;s HTML minification process\n<a href=\"https:\/\/github.com\/dgp1130\/blog\/commit\/e94a9c4c6efc39c36d8ba115925aa1891ca35f72\" target=\"_blank\">dropped a required space<\/a>.\nIf that doesn&#39;t prove that automated tools are worse for HTML&#39;s whitespace\nsemantics, I&#39;m not sure what does.<\/p>\n<h2 id=\"how-could-we-fix-this\">How Could we Fix This?<\/h2>\n<p>Since this is all so complicated and involved, it would be great to fix HTML so\nall these whitespace problems go away. Is that possible? What would it look\nlike?<\/p>\n<p>I don&#39;t have a perfect solution in mind, but I do have some thoughts. As I\nmentioned earlier, the root problem is that whitespace in HTML is ambiguous:\ndoes a space exist to support the developer authoring their HTML code, or to\ndisplay something reasonable to the end user? That question is unanswerable and\nis the core problem we should fix.<\/p>\n<p>The best way to do that is to change HTML syntax such that significant\nwhitespace is syntactically distinct from insignificant whitespace. The obvious\napproach is to do this just like every other programming language, quote your\nstrings!<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    \"Hello, World! My name is Devel and I've got a bone\"\n    \" to pick with HTML's whitespace behavior. It's\"\n    \" super confusing and no one understands it!\"\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>I see your disgusted reaction and honestly, I kinda get it. I don&#39;t think this\nlooks very good either and I wouldn&#39;t exactly want to write it. It&#39;s not\nparticularly elegant and I hate the leading spaces necessary on all but the\nfirst line - so inconsistent.<\/p>\n<p>In this proposed syntax, we at least have implicit concatenation like Python so\nyou don&#39;t need <code>+<\/code> signs everywhere. The idea is that all spaces inside the\nquotes are significant and retained for the user while all spaces outside the\nquotes are insignificant and used solely for the developer. Whitespace\ncharacters like tabs are allowed and preserved when used within quotes. Newlines\nare banned by default as it would be way too easy to forget a closing quote and\nintroduce unintended significant spacing. Therefore, a quoted newline is a\nsyntax error. An <code>&amp;lf;<\/code> HTML entity would allow newlines to be directly\nspecified or you could use a triple quote syntax to define a multi-line string.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    \"\"\"\n    Here is a newline.\n    And another newline.\n    One more for fun.\n    \"\"\"\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Lots of languages have triple quote syntax like this and my suggestion is to\nfollow\n<a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/csharp\/language-reference\/tokens\/raw-string\" target=\"_blank\">C#'s example<\/a>\nby making this &quot;indentation-aware&quot;. The opening and closing <code>&quot;&quot;&quot;<\/code> tokens need to\nbe the last \/ first tokens on their respective lines and the text content\nbetween them must be indented to match. Therefore the string above is identical\nto:<\/p>\n<pre><code>Here is a newline.\\nAnd another newline.\\nOne more for fun.\n<\/code><\/pre><p>This formats nicely while still allowing precise whitespace to be added where it\nis needed.<\/p>\n<p>Aside from adding quotes there&#39;s a couple other changes which need to be made:<\/p>\n<ol>\n<li>Any text outside of a quoted string is a syntax error.<ul>\n<li>Exactly how it renders is up to the browser, I really don&#39;t care what\nthe fallback behavior is given that browsers tend not to throw errors on\nbad HTML.<\/li>\n<li>The main point is that any tool is free to treat unquoted text as a\nsyntax error along the lines of <code>&lt;div &lt;span&gt;&gt;<\/code>.<\/li>\n<\/ul>\n<\/li>\n<li><code>white-space<\/code> needs to be removed\/reworked to always use the standard\nwhitespace behavior.<ul>\n<li>It can still control line wrapping and other presentational aspects,\nit&#39;s just the raw text content which should be consistent across all\noptions.<\/li>\n<li>This reduces the dependency on CSS to understand how HTML text is\nparsed.<\/li>\n<\/ul>\n<\/li>\n<li><code>&lt;pre&gt;<\/code> tags should be removed.<ul>\n<li>All text is preformatted (inside quotes), so having a special tag is no\nlonger needed.<\/li>\n<li>Formatting arbitrary user input into a quoted string is not meaningfully\nharder than HTML escaping the string already is today, so there&#39;s no\nvalue in keeping <code>&lt;pre&gt;<\/code> tags around.<\/li>\n<li>You could keep this as a backwards compatibility feature which is an\nexception to the &quot;no unquoted strings&quot; rule, but a purist implementation\nof this proposal would remove it entirely.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p>Would this solve the problem? Since whitespace is no longer ambiguous, we don&#39;t\nneed whitespace collapsing anymore. Whitespace outside the quotes is removed\naltogether, while whitespace inside the quotes is preserved. No collapsing\nneeded! Developers can add multiple spaces without needing <code>&amp;nbsp;<\/code>:<\/p>\n<pre><code class=\"language-html\"><span class=\"token comment\">&lt;!-- Just works! Indentation is correctly ignored, but\nspacing between the words is retained. --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n    \"Hello,        World!\"\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Prettier and other formatters can adjust the developer side of the whitespace as\nmuch as they want and even join\/split the string literals to move them across\nlines without changing the rendered output.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">class<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>wrapper<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">class<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>container<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>marketing-made-me-add-this<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token comment\">&lt;!-- Reformatted text to be shorter. --><\/span>\n            \"Hello, World! My name is Devel and I've\"\n            \" got a bone to pick with HTML's whitespace\"\n            \" behavior.\\nIt's super confusing and no\"\n            \" one understands how it works!\"\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Content management systems can be greatly simplified as well since there&#39;s no\nwhitespace behavior to understand or preserve. Whatever text marketing gives\njust gets wrapped in quotes and either replaces <code>\\n<\/code> with <code>&amp;lf;<\/code> or uses triple\nquotes. This way it outputs exactly the way marketing intended.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    \"\"\"\n    These shoes will make you the fastest* runner around!\n\n    * Not legally binding.\n    \"\"\"\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Minifiers also can just drop all the whitespace outside the quotes, then retain\nand join everything in the quotes together into a single line:<\/p>\n<pre><code class=\"language-html\"><span class=\"token comment\">&lt;!-- Before --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    \"Hello\"\n    \" World\"\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token comment\">&lt;!-- After --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\"Hello World\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Unfortunately this doesn&#39;t quite solve the\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#css\">Narrator issue discussed earlier<\/a>. Two strings still need to be treated\ndistinctly in a block formatting context, while strings would be implicitly\njoined in an inline formatting context.<\/p>\n<figure>\n    <figcaption>\n        Example 26: Quoted <code>block<\/code> vs <code>inline<\/code>.\n    <\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\"Re\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\"fri\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\"ger\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\"ator\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\"Re\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\"fri\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\"ger\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\"ator\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div>Re<\/div><div>fri<\/div><div>ger<\/div><div>ator<\/div>\n<br \/>\n<span>Re<\/span><span>fri<\/span><span>ger<\/span><span>ator<\/span><\/figure>\n\n<p>You need inline elements to join together so it&#39;s possible to style and control\nparts of words. For example, adding emphasis to only part of a word.<\/p>\n<figure>\n    <figcaption>Example 27: Emphasized part of word.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>em<\/span><span class=\"token punctuation\">><\/span><\/span>\"in\"<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>em<\/span><span class=\"token punctuation\">><\/span><\/span>\"conceivable!\"\n<\/code><\/pre><em>in<\/em>conceivable!<\/figure>\n\n<p>I don&#39;t see a good solution to that without completely reworking HTML&#39;s\nrendering model such that every tag has a statically-knowable formatting\ncontext, which is a much more complicated change to make.<\/p>\n<h3 id=\"dx-impact\">DX Impact<\/h3>\n<p>I get that lot of developers would probably push back on adding quotes to\neverything because of the negative developer experience (DX) impact. To preempt\nsome of those arguments, I&#39;ll remind you of a few points I&#39;ve hopefully made\nclear by now:<\/p>\n<ol>\n<li>Today&#39;s confusing whitespace rules is its own DX problem.<ul>\n<li>This proposal eliminates that problem and means you never have to deal\nwith a bad link underlines again.<\/li>\n<\/ul>\n<\/li>\n<li>HTML tooling becomes more stable.<ul>\n<li>It is no longer possible for source formatting to affect behavior.<\/li>\n<li>Less fighting with your formatter or debugging weird issues, more time\nsolving real problems.<\/li>\n<\/ul>\n<\/li>\n<li>HTML already breaks the rules of common text formatting.<ul>\n<li>The idea that you can write HTML today by just typing the text you want\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#isnt-html-just-a-document\">is a lie<\/a>.<\/li>\n<\/ul>\n<\/li>\n<li>Every other language already works this way.<ul>\n<li>Adding quotes would not suddenly make HTML unreasonably burdensome to\nwrite.<\/li>\n<li>Two more characters per element is not going to break your keyboard.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p>An alternative approach could use whitespace control characters like\n<a href=\"https:\/\/mozilla.github.io\/nunjucks\/templating.html#whitespace-control\" target=\"_blank\">Nunjuck's implementation<\/a>\nto achieve a different solution to this problem, however I think that actually\nleads to an <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#whitespace-control-characters\">overall worse DX<\/a>.<\/p>\n<h3 id=\"ship-it\">Ship It?<\/h3>\n<p>Since it seems to solve all the problems described, can we ship this?\nUnfortunately no.<\/p>\n<p>Shipping a breaking change of this magnitude to HTML would be functionally\nimpossible and go against many of the core principles of the open web. The best\nyou could do is introduce a new HTML parsing option which web pages could opt-in\nto along the lines of <code>&lt;!DOCTYPE html6&gt;<\/code>. Alternatively, you can treat this as\nan entirely DX problem and invent a new &quot;quoted HTML&quot; file format called\n<code>*.qhtml<\/code> with tooling to convert it to standard HTML. Even then, the ecosystem\neffects of this would be incredibly complicated and end up becoming a solution\nmore painful than the problem it&#39;s solving.<\/p>\n<p>So what could we ship?<\/p>\n<h3 id=\"non-collapsible-whitespace\">Non-Collapsible Whitespace<\/h3>\n<p>The one fix I can think of is to find a drop-in replacement for <code>&amp;nbsp;<\/code>. If\ndevelopers want a non-collapsible space which does not come with the baggage of\nnon-breaking and forced-width behavior, then we can come up with a new entity\nwhich meets those needs.<\/p>\n<p>My suggestion: <strong>Add a new, named HTML entity (<code>&amp;ncsp;<\/code>) as a regular space\nwhich does not get collapsed.<\/strong><\/p>\n<p>This would take on the non-collapsible benefits of <code>&amp;nbsp;<\/code>, while dropping the\nnon-breaking and forced-width behavior which leads to line wrapping issues. When\nyou &quot;just want to add a space&quot;, <code>&amp;ncsp;<\/code> is likely closer to what you actually\nwant and look better when line wrapped.<\/p>\n<p>Given the <a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#32\">layering of the HTML parser and CSS today<\/a>, I suspect this would\nactually require an entirely new Unicode character representing a\n&quot;non-collapsible space&quot;, distinct from the existing space character. Except\nUnicode is used in more than just HTML. In theory, other text rendering engines\nmay do some form of whitespace collapsing and a non-collapsible space might be\nuseful in some of those contexts, but I can see some push back to adding a new\ncharacter specifically to solve an HTML rendering bug.<\/p>\n<p>I <a href=\"https:\/\/github.com\/w3c\/csswg-drafts\/issues\/10821\" target=\"_blank\">filed an issue<\/a> with the\nCSS working group to discuss adding an <code>&amp;ncsp;<\/code> entity. Please share your own\nthoughts on this particular idea.<\/p>\n<p><strong>Addendum:<\/strong> I am aware the set of HTML entities is effectively closed and\nadding a new one is unlikely to happen. Don&#39;t overindex on <code>&amp;ncsp;<\/code>, the point\nis to have a specific syntax for defining an individual, non-collapsible space.\nWhether that&#39;s an HTML entity or anything else (<code>&lt;sp&gt;<\/code>?) is effectively an\nimplementation detail.<\/p>\n<h2 id=\"practical-advice\">Practical Advice<\/h2>\n<p>Given that we can&#39;t &quot;fix&quot; HTML, what can we do? Understanding the actual\nwhitespace behavior of HTML goes a long way, but as you&#39;ve probably figured out,\nit&#39;s surprisingly complicated and I don&#39;t think it really scales to expect\neveryone who writes HTML to fully understand this, nor would I expect a typical\ncode reviewer to spot whitespace bugs looking only at HTML code. Fortunately,\nHTML whitespace does <em>usually<\/em> work and we can often rely on that, it&#39;s mainly\nabout minimizing edge case behavior where you need to look up a blog post like\nthis. Rather than <em>preventing<\/em> unexpected collapsing behavior, we can <em>mitigate<\/em>\nthe issue to be less of a problem in practice. To that end, I have a few\nsuggestions, all of which use the term &quot;Avoid&quot; rather than &quot;Never&quot; since they\nare focused more on mitigation than prevention.<\/p>\n<h3 id=\"avoid-leading-and-trailing-whitespace-in-links\">Avoid Leading and Trailing Whitespace in Links<\/h3>\n<p>First, avoid leading and trailing whitespace in <code>&lt;a&gt;<\/code> tags or any other\nunderlined text.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    Here is some interesting text with\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>#<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>a link that exceeds the line length limit<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span>\n    but I don't care.\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>In my experience, links are by far the biggest challenges with whitespace given\nthat they are underlined by default and it&#39;s a common style. While spacing may\nbe incorrect in many other situations, the underline is usually where it becomes\na noticeable problem that needs to be fixed.<\/p>\n<p>As long as <code>&lt;a&gt;<\/code> tags are written with no leading or trailing whitespace, this\nisn&#39;t an issue and your underlines will always be correct. It does mean that in\nsome situations you might have to exceed the line length limit, and potentially\nfight with your formatter (don&#39;t use <code>--html-whitespace-sensitivity ignore<\/code>),\nbut I think it&#39;s worth it given how common of a foot gun this particular use\ncase is.<\/p>\n<h3 id=\"avoid-changing-layout-behavior-with-display\">Avoid Changing Layout Behavior with <code>display<\/code><\/h3>\n<p>Second, avoid changing <code>display<\/code> to a different layout behavior. If you want a\n<code>display: block;<\/code> element, pick a tag which uses <code>display: block;<\/code> by default.\nThis should reduce the possibility of your whitespace behavior being dependent\non CSS invisible to a formatter, however it might be difficult when you need a\nspecific semantic tag. Take for example, if you need an inline <code>&lt;aside&gt;<\/code> tag.\nThere are two ways to do this:<\/p>\n<ol>\n<li>Add a second tag so the one containing the text uses the correct <code>display<\/code>\nvalue by default, independent of the semantic <code>&lt;aside&gt;<\/code> tag wrapping it.<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n        My text content.\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>aside<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><\/li>\n<li>Pick a tag with the <code>display<\/code> behavior you want by default (<code>&lt;div&gt;<\/code> or\n<code>&lt;span&gt;<\/code>), and then use <code>role<\/code> to switch it to the semantic element you\nwant. There might be other accessibility implications to this though.<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span> <span class=\"token attr-name\">role<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>aside<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    My text content.\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><\/li>\n<\/ol>\n<p>Both of these approaches work with the <code>--html-whitespace-sensitivity css<\/code>\noption and avoid a CSS dependency just to understand the text displayed.<\/p>\n<p>Technically the same guidance should apply to\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#whitespace-of-flexbox-elements\">usage of flexbox and grid<\/a>, both of which\nforce their children to be block elements in a way formatters would be unable to\ndetect. Therefore <code>flex<\/code> and <code>grid<\/code> elements should always contain child tags\nwhich are block formatted by default (ex. use <code>&lt;div&gt;<\/code> instead of <code>&lt;span&gt;<\/code>), to\nalign with the formatter&#39;s expectations.<\/p>\n<h3 id=\"avoid-changing-collapsing-behavior-with-white-space\">Avoid Changing Collapsing Behavior with <code>white-space<\/code><\/h3>\n<p>Third, avoid <code>white-space: pre;<\/code> and prefer a real <code>&lt;pre&gt;<\/code> tag instead. Again,\nthis reduces dependencies on CSS and might not always be possible, but hopefully\nis a decent best-practice to follow.<\/p>\n<p>When you need to configure <code>white-space<\/code> to something other than <code>pre<\/code>, I\nrecommend only setting it on <code>&lt;pre&gt;<\/code> tags. The <code>&lt;pre&gt;<\/code> tag communicates to HTML\ntooling that its whitespace should be fully retained because its preformatted.\nEven if you&#39;re actually using a different <code>white-space<\/code> mode in your CSS, the\n<code>&lt;pre&gt;<\/code> tag is at least a key signal to HTML tooling that all whitespace should\nbe treated as significant.<\/p>\n<h3 id=\"avoid-insignificant-whitespace-in-pre-tags\">Avoid Insignificant Whitespace in <code>&lt;pre&gt;<\/code> Tags<\/h3>\n<p>Fourth, always write <code>&lt;pre&gt;<\/code> tags with no leading and trailing whitespace, and\nwithout indentation. They should generally look like:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">class<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>outer<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">class<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>inner<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>Some preformatted text\nwith a new line\nand some other content.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>pre<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Yeah, I don&#39;t like the look either. But this approach avoids the confusing\nleading\/trailing newline behavior and prevents indentation accidentally leaking\ninto the content.<\/p>\n<p>None of these suggestions really help HTML tooling maintainers unfortunately\nsince they still need to deal with whitespace regardless. But I warned you at\nthe start, this post is partially for sharing knowledge and partially for\nventing about how awful whitespace in HTML actually is.<\/p>\n<p>Broken? Yes.<\/p>\n<p>Fixable? Not really.<\/p>\n<p>Manageable?<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 498 \/ 244; max-height: 244px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"498\" height=\"244\" class=\"gif\" style=\"aspect-ratio: 498 \/ 244; max-height: 244px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/im-gonna-complain.webm\" type=\"video\/webm\" \/>\n        <source src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/im-gonna-complain.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"498\" height=\"244\" class=\"gif\" style=\"aspect-ratio: 498 \/ 244; max-height: 244px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/im-gonna-complain.webm\" type=\"video\/webm\" \/>\n        <source src=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/im-gonna-complain.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>Shout out to <a href=\"https:\/\/knowler.dev\/\" target=\"_blank\">Nathan Knowler<\/a> who helped me understand the\nlayering between HTML and CSS, precise behavior of <code>&amp;nbsp;<\/code>, as well as some of\nthe finer points of the <code>white-space<\/code> property.<\/p>\n<h2 id=\"appendix\">Appendix<\/h2>\n<h3 id=\"whitespace-of-flexbox-elements\">Whitespace of Flexbox Elements<\/h3>\n<p>Did you know that flexbox creates even more unique whitespace behavior? Here&#39;s\nthe same code sample, with and without <code>display: flex;<\/code>.<\/p>\n<figure>\n    <figcaption>Example 28: Block with <code>&lt;div&gt;<\/code> children.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>First<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Second<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div>\n    <div>First<\/div>\n    <div>Second<\/div>\n<\/div><\/figure>\n\n<figure>\n    <figcaption>Example 29: Flexbox with <code>&lt;div&gt;<\/code> children.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> flex<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>First<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Second<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div style=\"display: flex;\">\n    <div>First<\/div>\n    <div>Second<\/div>\n<\/div><\/figure>\n\n<p><code>display: flex;<\/code> lays out in the inline axis by default, typically horizontally.\nEven though we have block elements in the <code>&lt;div&gt;<\/code> children, they are placed on\nthe same line. Note the lack of visible whitespace between the elements. Since\nwhitespace between block elements are treated as blocks of whitespace\nelements, they follow the same rule of &quot;No empty blocks&quot; and are removed,\ntherefore the whitespace before the <code>&lt;div&gt;<\/code> children is considered\ninsignificant.<\/p>\n<p>Let&#39;s try the same thing with <code>&lt;span&gt;<\/code> tags!<\/p>\n<figure>\n    <figcaption>Example 30: Flexbox with <code>&lt;span&gt;<\/code> children.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> flex<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>First<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Second<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div style=\"display: flex;\">\n    <span>First<\/span>\n    <span>Second<\/span>\n<\/div><\/figure>\n\n<p>Here we see that the flex behavior actually didn&#39;t change at all. The <code>&lt;span&gt;<\/code>\nelements are still side by side <em>and<\/em> there is no whitespace between them. But\ndon&#39;t inline elements preserve spaces between them?<\/p>\n<p>This is because flexbox children create new block formatting contexts by\ndefault.\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/CSS\/CSS_display\/Block_formatting_context\" target=\"_blank\">Quoting MDN again<\/a>:<\/p>\n<blockquote>\n<p>A block formatting context is created by at least one of the following:<\/p>\n<ul>\n<li>[...]<\/li>\n<li>Flex items (direct children of the element with <code>display: flex<\/code> or\n<code>inline-flex<\/code>) if they are neither <code>flex<\/code> nor <code>grid<\/code> nor <code>table<\/code>\ncontainers themselves.<\/li>\n<\/ul>\n<\/blockquote>\n<p>This means each child gets its own block rendering context, regardless of the\ndefault behavior of its tag. Therefore, whitespace between them is dropped, even\nthough we&#39;re using <code>&lt;span&gt;<\/code> elements which are natively <code>display: inline;<\/code>. Grid\nactually works the same as flexbox in this respect too.<\/p>\n<p>What this tells us is that not only can CSS inform the whitespace processing\nbehavior of an HTML element, but the CSS of a <em>different<\/em> element can have the\nsame influence.<\/p>\n<p>This is especially problematic if you&#39;re writing HTML fragments or partials. If\nyou write a file which is not a full HTML page but just a small part of it, and\nstart that file off with a <code>&lt;span&gt;<\/code> tag, it is actually unknowable what the\n<code>display<\/code> value of that <code>&lt;span&gt;<\/code> will be.<\/p>\n<pre><code class=\"language-html\"><span class=\"token comment\">&lt;!-- my-component.html --><\/span>\n\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>I'm inline right?<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>This is because you can&#39;t know what the <em>parent<\/em> of that <code>&lt;span&gt;<\/code> tag will be.\nIf the parent is a <code>&lt;div&gt;<\/code>, then it will use <code>display: inline;<\/code> like <code>&lt;span&gt;<\/code>\nnaturally does. If it is a flexbox or grid, then it will be <code>display: block;<\/code>.<\/p>\n<pre><code class=\"language-html\"><span class=\"token comment\">&lt;!-- my-other-component.html --><\/span>\n\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token special-attr\"><span class=\"token attr-name\">style<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span><span class=\"token value css language-css\"><span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> flex<span class=\"token punctuation\">;<\/span><\/span><span class=\"token punctuation\">\"<\/span><\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token comment\">&lt;!-- Nope, you're a block now. --><\/span>\n    ${render('.\/my-component.html')}\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>The correct answer depends on how that\nHTML partial is used and can even differ across multiple usages of the same\npartial!<\/p>\n<h3 id=\"whitespace-of-inline-block-elements\">Whitespace of <code>inline-block<\/code> Elements<\/h3>\n<p>There&#39;s even <em>more<\/em> nuanced whitespace behavior for <code>inline-block<\/code>!\n<code>inline-block<\/code> elements are treated as inline on the outside and block on the\ninside. This means whitespace between <code>inline-block<\/code> elements can be\nsignificant just like it is for <code>inline<\/code> elements.<\/p>\n<p>Let&#39;s look at\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Document_Object_Model\/Whitespace#example_3\" target=\"_blank\">this example from MDN<\/a>\nwith a couple boxes.<\/p>\n<figure>\n    <figcaption>\n        Example 31: <code>&lt;inline-block&gt;<\/code> with whitespace.\n    <\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>style<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token style\"><span class=\"token language-css\">\n    <span class=\"token selector\">li<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> inline-block<span class=\"token punctuation\">;<\/span>\n        <span class=\"token property\">width<\/span><span class=\"token punctuation\">:<\/span> 2em<span class=\"token punctuation\">;<\/span>\n        <span class=\"token property\">height<\/span><span class=\"token punctuation\">:<\/span> 2em<span class=\"token punctuation\">;<\/span>\n        <span class=\"token property\">background<\/span><span class=\"token punctuation\">:<\/span> red<span class=\"token punctuation\">;<\/span>\n        <span class=\"token property\">border<\/span><span class=\"token punctuation\">:<\/span> 1px solid black<span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>style<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n  <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n  <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><ul class=\"inline-block-list\">\n  <li><\/li>\n  <li><\/li>\n<\/ul><\/figure>\n\n<p>You should see a small space between the two boxes. I&#39;ve blown up the font size\nto make this space more visible. But where does that space come from? There&#39;s no\nmargin or padding here. In fact, what if we change the HTML ever so slightly...<\/p>\n<figure>\n    <figcaption>\n        Example 32: <code>&lt;inline-block&gt;<\/code> without whitespace.\n    <\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n  <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><ul class=\"inline-block-list\">\n  <li><\/li><li><\/li>\n<\/ul><\/figure>\n\n<p>Shout out to any developers who had to debug that spacing issue. And also shout\nout to Firefox which actually displays a &quot;whitespace&quot; element in its DevTools to\nmake this somewhat visible.<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/demos\/2-ff-whitespace.avif\" type=\"image\/avif\" width=\"894\" height=\"635\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/demos\/2-ff-whitespace.png\" alt=\"Screenshot of Firefox rendering a web page with two pairs of boxes like above. The first pair does not contain any spacing between them, while the second pair does. DevTools is open to the &quot;Inspector&quot; panel showing the rendered DOM. It contains two `<ul>` tags, each containing two `<li>` tags representing each box. The elements are formatted in this view, so the whitespace around each of them is meaningless. However between the two `<li>` tags in the second `<ul>` is a small element labeled &quot;whitespace&quot;. The user has clicked on this element and the spacing between the second pair of boxes is highlighted and marked as `#text`, indicating exactly where that spacing is coming from.\" width=\"894\" height=\"635\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<h3 id=\"32\"><code>&amp;#32;<\/code><\/h3>\n<p>If <code>&amp;nbsp;<\/code> doesn&#39;t work, what can you do instead? Ideally, you could just use a\nregular space since that would naturally avoid introducing the non-breaking\nbehavior and allow it to be zero-width when line wrapped. However HTML\nwhitespace collapsing prevents you from just inserting arbitrary spaces wherever\nyou want, especially if you want multiple adjacent spaces.<\/p>\n<p>My immediate intuition was to reach for <code>&amp;#32;<\/code>. If you didn&#39;t know, <code>&amp;nbsp;<\/code> is\na <em>named<\/em> HTML entity, however there are unnamed entities as well. Specifically,\nyou can use <code>&amp;#&lt;num&gt;;<\/code> to get the character at that Unicode value. 32 happens to\nbe the Unicode value of a standard space, so we can use <code>&amp;#32;<\/code> just like a\nspace character.<\/p>\n<p>Unfortunately it&#39;s so equivalent that it&#39;s also subject to the same whitespace\ncollapsing behavior. So you can put as many <code>&amp;#32;<\/code> as you want, you&#39;ll still\nget at most only one space. My sincerest apologies to the three people reading\nthis who want to put two spaces after the end of a sentence.<\/p>\n<figure>\n    <figcaption>Example 33: <code>&amp;#32;<\/code> spaces.<\/figcaption>\n\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Hello<span class=\"token entity\" title=\"&#32;\">&amp;#32;<\/span><span class=\"token entity\" title=\"&#32;\">&amp;#32;<\/span><span class=\"token entity\" title=\"&#32;\">&amp;#32;<\/span><span class=\"token entity\" title=\"&#32;\">&amp;#32;<\/span><span class=\"token entity\" title=\"&#32;\">&amp;#32;<\/span><span class=\"token entity\" title=\"&#32;\">&amp;#32;<\/span>World!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><div>Hello&#32;&#32;&#32;&#32;&#32;&#32;World!<\/div><\/figure>\n\n<p>This behavior actually feels objectively wrong to me. Whitespace collapsing is a\naffordance for the developer experience so you don&#39;t have to butcher your HTML\ncode to get a reasonable output. But if the developer hand-writes <code>&amp;#32;<\/code>, they\nclearly care about rendering a space in that slot and are giving up a convenient\nDX to do it. Whatever developer writes multiple <code>&amp;#32;<\/code> almost certainly does\nnot expect them to be collapsed together.<\/p>\n<p>I wasn&#39;t able to come up with a compelling reason for why a developer would want\n<code>&amp;#32;<\/code> to be collapsible, but I think I do understand why it works this way. As\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-whitespace\/#css\">mentioned earlier<\/a>, CSS controls whitespace collapsing, not the HTML\nparser. This means the HTML parser needs to convert <code>&amp;#32;<\/code> to literal spaces\nand retain <em>all<\/em> of them for all elements. It&#39;s then up to CSS to decide which\nspaces are significant. Because of that, CSS can&#39;t distinguish between a literal\nspace and a <code>&amp;#32;<\/code> entity, they&#39;re the same thing (Unicode character 32 to be\nprecise).<\/p>\n<p>I can see an argument that this actually is desirable for purposes of\nconsistency. On a certain level, a literal space and <code>&amp;#32;<\/code> <em>should<\/em> be\nindistinguishable and lead to the same behavior. However, I think that&#39;s a\nstronger argument for how the spaces are observable at runtime, not how the HTML\nparser interprets the code. I think it would be reasonable for the HTML parser\nto distinguish a space character and a <code>&amp;#32;<\/code> entity to use different\ncollapsing behaviors. For example, <code>&lt;<\/code> and <code>&amp;lt;<\/code> are not the same because the\nformer starts an HTML tag while the later is a text literal for <code>&lt;<\/code> which\nexplicitly does <em>not<\/em> start an HTML tag. Unfortunately the HTML parser isn&#39;t the\none doing the collapsing, so we&#39;ve lost that information by the time CSS handles\nit. This &quot;bug&quot; with <code>&amp;#32;<\/code> feels like a side-effect of the decision to allow\nCSS to influence whitespace behavior.<\/p>\n<h3 id=\"isnt-html-just-a-document\">Isn&#39;t HTML Just a Document?<\/h3>\n<p>One potential advantage to the way HTML whitespace works is that it makes the\nformat more accessible to non-developers. HTML was intended to represent\ndocuments, so just look for the text you want to modify and then update it to\nwhatever new text you want to use. Don&#39;t worry about the syntax at all!<\/p>\n<p>That sounds great in theory, but it&#39;s also not true. A core aspect of writing\nplain text is the spacing and formatting of that text. Yet HTML breaks even the\nmost basic rules of how text can be formatted. Take this example of some text a\nnon-developer might try to write without any knowledge of HTML and how it\nactually renders when thrown into a document unmodified.<\/p>\n<figure>\n    <figcaption>34. Plain text.<\/figcaption>\n\n<pre><code>First:  Say &quot;hello&quot;.\nSecond: Say &quot;world&quot;.\n\nHere&#39;s my shopping list for today:\n&gt; Apples\n&gt; Oranges\n&gt; Bananas\n<\/code><\/pre>First:  Say \"hello\".\nSecond: Say \"world\".\n\nHere's my shopping list for today:\n> Apples\n> Oranges\n> Bananas<\/figure>\n\n<p>Everything gets rendered onto one line, <code>\\n<\/code> is effectively meaningless and\ndropped entirely. <code>First:<\/code> had two spaces to align with <code>Second:<\/code>, but they are\ncollapsed together. The list format is completely destroyed. This is all without\nmentioning that you should escape <code>&gt;<\/code> into <code>&amp;gt;<\/code>, so I would argue it&#39;s almost\na security issue to think of HTML in this mindset in the first place. This kind\nof use case requires <code>&lt;pre&gt;<\/code> tags which completely changes the behavior of\neverything.<\/p>\n<p>Text documents have two intrinsic features to support formatting: spaces and\nnewlines. HTML breaks both of those features with whitespace collapsing. You\ncan&#39;t blindly copy-paste from any other text document into an HTML page and\nexpect any kind of sane behavior. Where non-developers do write text content\nwhich is rendered in HTML web pages, they typically do it through a content\nmanagement system (CMS), not by hand-writing HTML files anyways.<\/p>\n<p>You can&#39;t think of HTML code like a plain text document.<\/p>\n<h3 id=\"whitespace-control-characters\">Whitespace Control Characters<\/h3>\n<p>If you really don&#39;t like quoting strings in HTML, one potential alternative\napproach to is to borrow an idea from HTML preprocessors which have whitespace\ncontrol characters. For example, <a href=\"https:\/\/mozilla.github.io\/nunjucks\/\" target=\"_blank\">Nunjucks<\/a>\nuses <code>{% expr %}<\/code> to denote block interpolations, but you can use <code>{%- expr -%}<\/code>\nto\n<a href=\"https:\/\/mozilla.github.io\/nunjucks\/templating.html#whitespace-control\" target=\"_blank\">trim whitespace<\/a>\nsurrounding the content.<\/p>\n<pre><code class=\"language-njk\">First\n{%- if (false) -%}\n    Second\n{%- endif -%}\nThird\n<\/code><\/pre><p>Here, the whitespace around the <code>if<\/code> and <code>endif<\/code> are unused, meaning this will\noutput:<\/p>\n<pre><code class=\"language-inlinehtml\">FirstThird\n<\/code><\/pre><p>Without the <code>{%- ... -%}<\/code>, developers would be forced into a space between the\ntwo words, or required to write their <code>if<\/code> statement on a single line.<\/p>\n<p>You could add a similar syntax to HTML to trim whitespace around particular\nelements, maybe <code>&lt;-tag-&gt;<\/code> and <code>&lt;-\/tag-&gt;<\/code>? I don&#39;t know, that looks way worse\nthan quotes to me...<\/p>\n<p>I don&#39;t hate this approach, as it does remove the general ambiguity around\nwhether any given space is significant or not and if that&#39;s more palatable to\nthe community I could probably be talked into it some form of this being applied\nto HTML.<\/p>\n<p>However it doesn&#39;t address the issue of interior whitespace such as multiple\nadjacent spaces or spaces from a CMS tool. We&#39;d also still need to make the\nsuggested changes to decouple CSS from whitespace-processing behavior.<\/p>\n<p>I also don&#39;t care for this approach because I believe it shifts the burden of\nunderstanding whitespace to the developer. They need to recognize &quot;Oh, in this\nsituation I need to use a <code>&lt;-tag&gt;<\/code> because the whitespace after it is important,\nbut the whitespace before isn&#39;t&quot;. I think just requiring quotes would make this\nmuch more obvious to most developers who would get their spacing right the first\ntime, rather than opting into special syntax to fix the problem afterwards.<\/p>\n<p>I do see the impact of quotes to the general DX of HTML and I understand the\nknee-jerk emotional reaction of a lot of developers. That said, I honestly\nbelieve quotes would be a net DX <em>improvement<\/em>, even if it does result in more\ntyping.<\/p>\n"},{"title":"How a Cat Debugged Stable Diffusion","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/"}},"updated":"2023-12-17T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/","content":"<h1 id=\"how-a-cat-debugged-stable-diffusion\">How a Cat Debugged Stable Diffusion<\/h1>\n<time datetime=\"2023-12-17T19:00:00.000Z\" class=\"timestamp\">December 17, 2023<\/time><p>This is the story of how I needed help to solve a tricky bug. Now, that happens\nall the time. I rely on coworkers and the web community to help me with bugs\nquite frequently. But this one was unique because it wasn&#39;t just any colleague,\nit was my cat Ollie, specifically this asshole stealing my chair:<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/ollie.avif\" type=\"image\/avif\" width=\"1024\" height=\"768\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/ollie.webp\" alt=\"A long-haired, brown tabby cat lays in an office chair. He is twisted around on his back and looking at the viewer upside down. His front paws are held out in the air as he seems to be saying &quot;You can't possibly kick someone THIS cute out of a chair YOU gave up by leaving for more than 5 seconds.&quot;\" width=\"1024\" height=\"768\" decoding=\"async\" loading=\"eager\" fetchpriority=\"high\" \/>\n<\/picture><\/p>\n<p>I was interested in experimenting with AI image generation. Not for any\nparticular use case, just doing it for fun. I could use any number of existing\nweb sites to do this, but pretty much all of them require some form of login or\npayment and as I have\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/#service-worker-server\">previously established on this blog<\/a>,\nI am too cheap to do that. So instead I went with the pro hacker move of trying\nto run <a href=\"https:\/\/github.com\/Stability-AI\/stablediffusion\/\" target=\"_blank\">Stable Diffusion<\/a> on\nmy computer locally.<\/p>\n<p>This took most of the day and required multiple approaches and many failed\nattempts, but I did eventually get it installed via the <em>very cool<\/em>\n<a href=\"https:\/\/github.com\/AUTOMATIC1111\/stable-diffusion-webui\/\" target=\"_blank\"><code>stable-diffusion-webui<\/code><\/a> project. Excited, I immediately start generating a picture of a litter of\nkittens cuddling and sleeping together, because what else could I possibly\ngenerate?<\/p>\n<p>Suddenly the microwave timer goes off. Food is done I guess. I didn&#39;t realize my\npartner was heating up dinner already, it is a little early for that.\nMicrowave&#39;s tone sounds a bit off too, I hope it isn&#39;t broken or something.<\/p>\n<p>But more importantly, I now have a cute (if a little creepy) picture of kittens!<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/kittens.avif\" type=\"image\/avif\" width=\"512\" height=\"483\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/kittens.webp\" alt=\"Four kittens fill the entire image, uncomfortably close to one another. Each cat looks almost like they were copy-pasted from the same base. They are mostly white on the paws and chest, dark on the back, with some streaks of orange on the head. The eyes are off in an inexplicable, uncanny way.\" width=\"512\" height=\"483\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<p>I immediately bump up the batch size to make a handful of them and restart.<\/p>\n<p>Then the microwave goes off again. That&#39;s weird, it&#39;s only been maybe 30\nseconds since the last time. I guess the food wasn&#39;t quite warm enough?<\/p>\n<p>This generation takes maybe a minute due to the larger batch size. Except, the\nmicrowave doesn&#39;t stop. It just keeps going. A long, loud BEEEEEEEEEP.<\/p>\n<p>Oh crap, the microwave&#39;s broken. Wait, not the microwave, but the computer? This\nlong and horrendously loud beep was coming from my workstation?! Generating an\nimage was apparently so stressful on my computer that it was forced to let out a\nstrained squeal of frustration\u2014a cry for help.<\/p>\n<p>I hastily apologize to the computer before our future AI overloads hear about\nthis war crime I just committed. But now the hunt is on: how is Stable Diffusion\ncausing my computer to beep like this?<\/p>\n<p>I immediately run to Google and even post to a few forums for suggestions about\nwhat to look for. I&#39;m more of a software guy and was never that in to hardware.\nWhat do I even search for here: &quot;stable diffusion computer beep loud&quot;?<\/p>\n<p>A few potential causes quickly come to my attention:<\/p>\n<p><strong>Could this sound be &quot;coil whine&quot;?<\/strong> Almost everything I read immediately\nsuggests\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Electromagnetically_induced_acoustic_noise\" target=\"_blank\">\"coil whine\"<\/a>\nas a likely culprit. This can happen due to vibrations of components caused by\nan electric current. I look up a few videos of that, but they don&#39;t sound\nanything like what I&#39;m hearing. Those videos sound like a standard electrical\nhum\u2014just loud enough to be annoying. My computer sounds like a pig fleeing its\nown slaughter. Seriously, listen to this video and tell me with a straight face\nthat it sounds anything like coil whine:<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/demo.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/demo.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p><strong>Is my machine not powerful enough for Stable Diffusion?<\/strong> This computer is\nrocking an RTX 3080, with 32 GB of RAM, is that really not good enough? I have\nrun big code compilations before. <a href=\"https:\/\/bazel.build\/\" target=\"_blank\">Bazel<\/a> can be fairly\nresource hungry and I even\n<a href=\"https:\/\/techhub.social\/@develwithoutacause\/111513699508070036\" target=\"_blank\">built V8 (really d8) from source<\/a>\nthe other day. I have run modern video games on max settings and done a touch of\nvideo editing. This machine isn&#39;t winning any awards, but it&#39;s a beefy box, and\nI have never heard more than a gentle hum from it before. These image generation\njobs take seconds to complete, not minutes. Resources don&#39;t seem like the issue.<\/p>\n<p><strong>Is the GPU overheating?<\/strong> The sound emits immediately when generating an\nimage, there is no time for the computer to heat up. I double check the\ntemperature and it is running at a pretty reasonable 60\u00b0C. The CPU is in a\nsimilar state.<\/p>\n<p><strong>Is the fan messed up? Maybe a bearing came loose?<\/strong> Well, the machine is\nmostly liquid cooled, but does have a couple fans for air flow. They look fine\non inspection and again, the sound is immediate, no time for them to spin up to\na bad frequency or for the machine to get overheated.<\/p>\n<p><strong>Is there a speaker in the box?<\/strong> This was a pre-built machine, but I picked\nthe parts for it myself. Unless the builder snuck in a speaker, or one was\nincluded on the motherboard, I can&#39;t imagine there is any audio device in there.<\/p>\n<p><strong>Is the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Bell_character\" target=\"_blank\">terminal bell<\/a> being forced on at max volume?<\/strong>\nI have never heard a terminal bell for longer than a single beep, but maybe that\nis possible? I am pretty sure I disabled it, because seriously, who <em>actually<\/em>\nwants an audible beep from their terminal? Testing it now I cannot even get it\nto ring once intentionally.<\/p>\n<p>What component is actually beeping anyways? I pull the side panel off my\ncomputer and generate 100 images just to hear the sound and try to trace where\nit is coming from.<\/p>\n<p>Is the power supply overloaded? Could the sound be coming from there? I don&#39;t\nthink so, but the sound is so loud it feels like it is coming from the whole\ncomputer. Maybe the motherboard? Could that have a speaker built into it? That\nmust be terrible for acoustics, but maybe useful for a little beep when\nsomething is wrong?<\/p>\n<p>While I&#39;m on the floor asking my nonverbal computer to point to where it hurts,\nOllie suddenly rushes into the room seemingly attracted by the noise. He hurries\nover to my computer, confused and annoyed, wondering what woke him up. I gently\npush him away from the computer to avoid getting even <em>more<\/em> of his fur inside\nthe box. Seriously, how does a single cat shed so much?<\/p>\n<p>But Ollie ignores the computer altogether. He goes around the machine and peeks\nbehind my desk, sniffing around. What does he hear, I wonder?<\/p>\n<p>Then, without hesitation, Ollie lifts his paw and starts aggressively whacking\nmy surge protector, as if shouting <strong>&quot;SHUT THE F--- UP!&quot;<\/strong><\/p>\n<p>I quickly pull Ollie away before he electrocutes himself and banish him from the\noffice. I hurry back and push the computer out of the way to listen. He&#39;s right,\nit&#39;s not the computer, it&#39;s the surge protector!<\/p>\n<p>But this isn&#39;t just any surge protector. I have an\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Uninterruptible_power_supply\" target=\"_blank\">uninterruptible power supply (UPS)<\/a>.\nIt is basically a surge protector with a big battery in it. So if the power goes\nout, it automatically falls back to the battery and you can still squeeze\nanother X hours of juice out of it until the main power comes back on.<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/ups.avif\" type=\"image\/avif\" width=\"450\" height=\"345\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/ups.webp\" alt=\"An uninterruptible power supply. It looks like a standard surge protector, but is shaped like a brick and significantly larger.\" width=\"450\" height=\"345\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<p>I&#39;m not running an always-online server on it or anything like that. I just get\na surprising number of power fluctuations my area (shout out to PG&amp;E). Those\nfluctuations make my office lamp flicker which can give me a headache and\nsometimes the power is out just long enough that the computer shuts down. The\nUPS is supposed to keep the computer alive through that couple-second outage.<\/p>\n<p>So if the power supply is complaining, does that mean Stable Diffusion is\npulling too much energy? I quickly check my system specs. My computer&#39;s power\nsupply is a Seasonic FOCUS GM-750W Gold. Just like it says in the name, it maxes\nout at 750 watts. Meanwhile the UPS was only rated for up to <em>360 watts<\/em>.\nLooking at the manual, the UPS emits a loud beep whenever it&#39;s running out of\nbattery\u2014or in this case, <em>being overdrawn<\/em>.<\/p>\n<p>$200 later and after swapping a massive battery for an even more massive\nbattery, I&#39;m now able to run Stable Diffusion without my workstation screaming\nin utter horror.<\/p>\n<p><strong>Public Service Announcement: Check your power usage before you buy a UPS.<\/strong><\/p>\n<p>So that answers it: Stable Diffusion was forcing my machine to pull so much\npower that it tripped my UPS. Since it was right behind my computer, I couldn&#39;t\npinpoint where the sound was coming from and it took Ollie&#39;s keen ears to find\nthe true culprit. Who knew cats could be so good at debugging? I swear Ollie is\nway too smart for his own good and is now apparently better at debugging than I\nam. Perhaps software developers should be less worried about AI stealing our\njobs and more worried about felines swiping them away.<\/p>\n<p>Unfortunately I didn&#39;t capture Ollie going to battle with my surge protector on\ncamera and I&#39;m not skilled enough to draw it. But I <em>do<\/em> now have an AI which\ncan visualize what this looked like:<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/battle.avif\" type=\"image\/avif\" width=\"512\" height=\"512\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/cat-debugging\/battle.webp\" alt=\"A black cat (?) jumps on top of a green box with its paws in the air about to swipe, drawn in an animated cartoon style. The cat's face is deformed with odd lines for eyes and the box doesn't seem to clearly identify as anything in particular, just a strange off-green color with some arbitrary switches and plugs in it.\" width=\"512\" height=\"512\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<p>Maybe it&#39;s the AI who should be afraid.<\/p>\n"},{"title":"HTML Fragments Routing","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/"}},"updated":"2023-01-24T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/","content":"<h1 id=\"html-fragments-routing\">HTML Fragments Routing<\/h1>\n<time datetime=\"2023-01-24T19:00:00.000Z\" class=\"timestamp\">January 24, 2023<\/time><p>Another blog post about <a href=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/\">HTML fragments<\/a> for you. If you\nhaven&#39;t read the <a href=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/\">previous<\/a>\n<a href=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/\">ones<\/a>, I suggest you do because they are\nreally interesting and probably the most popular thing on this blog right now.\nTens of people can&#39;t be wrong about something like that!<\/p>\n<p>For those of you that didn&#39;t click the links above \ud83d\ude22, the TL;DR: for HTML\nfragments is basically &quot;What if servers just rendered a single,\nfully-encapsulated component. Could we use that on the client without any\nspecial integration or tooling?&quot; In practice this looks like serving:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-counter<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>template<\/span> <span class=\"token attr-name\">shadowroot<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>open<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>The current count is: <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>5<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>button<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>decrement<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>-<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>button<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>increment<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>+<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>style<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token style\"><span class=\"token language-css\"><span class=\"token selector\">:host<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token property\">display<\/span><span class=\"token punctuation\">:<\/span> block<span class=\"token punctuation\">;<\/span> <span class=\"token punctuation\">}<\/span><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>style<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/my-counter.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>template<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-counter<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>And then requesting and appending it to the DOM like so:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> parseDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/see-html-fragments-post.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> response <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/my-counter\/'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> fragment <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>response<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\ndocument<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">appendChild<\/span><span class=\"token punctuation\">(<\/span>fragment<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneContent<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Well at some point I got the idea: &quot;What if servers just rendered a single\n<strong>route<\/strong>? Could we use that on the client without any special integration or\ntooling?&quot; This is essentially trying to build a router on top of HTML fragments,\nwhere clicking a link fetches <em>just the page content<\/em> as an HTML fragment and\nthen performs a same page navigation by replacing the current page content with\nthe result.<\/p>\n<p>Most web sites have a singular &quot;frame&quot; around the main content of its pages. The\nframe includes the header, navigation, sidebar, footer, login status, and more.\nHowever the only thing which meaningfully changes between routes is the core\npage content, usually the stuff inside the <code>&lt;main&gt;...&lt;\/main&gt;<\/code> element. So let&#39;s\ndefine the page content as an HTML fragment which can be rendered independently\nby the server. Is it possible for the client to use this and perform same-page\nnavigations, allowing full server-side rendering in single-page applications?<\/p>\n<p>The initial navigation works just like always, the browser requests a page and\ngets both the page &quot;frame&quot; and its content. However on subsequent navigations,\nthe browser should only request the <em>content<\/em> of the new page, not including the\nframe. That content is then swapped in to the existing page, keeping all the\nexisting JavaScript state and reusing the existing frame from the first request.<\/p>\n<p><picture>\n    \n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/sequence-diagram.svg\" alt=\"A sequence diagram demonstrating a browser requesting the index page of a website, where the server returns the full page HTML content. The user then clicks a link and the browser requests the `\/about\/` page. The server only returns `<p>About me...<\/p>`, not the full HTML page.\" decoding=\"async\" loading=\"eager\" fetchpriority=\"high\" class=\"large\" \/>\n<\/picture><\/p>\n<h2 id=\"example-router\">Example Router<\/h2>\n<p>This problem space is roughly broken up into three areas we need to handle:<\/p>\n<ol>\n<li>Serve only page content when requested.<\/li>\n<li>Create a router component.<\/li>\n<li>Render a page with the router.<\/li>\n<\/ol>\n<h3 id=\"server-side-rendering\">Server-side Rendering<\/h3>\n<p>If the user visits <code>\/home<\/code> in their browser, the server will receive a request\nfor <code>\/home<\/code> and it needs to interpret that as the initial navigation. However,\nwhen the user performs a same-page navigation to <code>\/about<\/code>, the router only wants\nthe main page content. The user could also visit these pages in the opposite\norder, starting at <code>\/about<\/code> and then navigating to <code>\/home<\/code>. In either case, the\napplication should do a full page render for the first route, and then all\nsubsequent routes should be done using the HTML fragment of the new route&#39;s\ncontent.<\/p>\n<p>This means we need the server to support rendering a page in both contexts. It\nmust render the full page for the initial browser navigation, but then all\nsubsequent same-page navigations need to only return the page content. This is\nextra complicated because once the user has performed a same-page navigation to\n<code>\/about<\/code>, they may refresh the page and the browser will expect to receive the\nfull page and its frame from scratch.<\/p>\n<p>We can implement this through many different mechanisms, but the most\nstraightforward one is a query parameter. In this example, let&#39;s set up the\nserver to check for a <code>?fragment<\/code> query parameter and use that to decide what\nit&#39;s output should be. If the <code>?fragment<\/code> query parameter is set, the server\nwill return only the page&#39;s main content, without the frame. If the <code>?fragment<\/code>\nquery parameter is missing, then it must be the browser&#39;s initial navigation and\nthe full page including the frame is needed.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">function<\/span> <span class=\"token function\">serveAboutPage<\/span><span class=\"token punctuation\">(<\/span>request<span class=\"token operator\">:<\/span> Request<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Response <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> isRequestingFragment <span class=\"token operator\">=<\/span>\n        <span class=\"token keyword\">new<\/span> <span class=\"token class-name\"><span class=\"token constant\">URL<\/span><\/span><span class=\"token punctuation\">(<\/span>request<span class=\"token punctuation\">.<\/span>url<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span>searchParams<span class=\"token punctuation\">.<\/span><span class=\"token function\">has<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'fragment'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>isRequestingFragment<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ Only return the about page's main content.<\/span>\n        <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Response<\/span><span class=\"token punctuation\">(<\/span><span class=\"token function\">renderAboutContent<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">else<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ Return the full page, include the frame.<\/span>\n        <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Response<\/span><span class=\"token punctuation\">(<\/span>\n            <span class=\"token function\">renderPageFrame<\/span><span class=\"token punctuation\">(<\/span><span class=\"token function\">renderAboutContent<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><h3 id=\"router-component\">Router Component<\/h3>\n<p>The next problem is that we need to build a router aware of HTML fragments which\nunderstands how to use the <code>?fragment<\/code> query parameter. This is mostly tackled\nby a <code>BaseRouter<\/code> custom element class. We can extend this class and then\noverride the <code>route()<\/code> method to fetch a new route from the server and return it\nas a <code>DocumentFragment<\/code>. This allows us to specify how to translate a route into\nthe fragment displayed to the user, and gives an opportunity to use the\n<code>?fragment<\/code> query parameter.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> parseDomFragment<span class=\"token punctuation\">,<\/span> BaseRouter<span class=\"token punctuation\">,<\/span> Route <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/**\n * Application router. Requests all routes with the\n * `?fragment` query parameter.\n *\/<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Router<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">BaseRouter<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/** Fetch a `Route` from the server and return it's fragment. *\/<\/span>\n    <span class=\"token keyword\">protected<\/span> override <span class=\"token keyword\">async<\/span> <span class=\"token function\">route<\/span><span class=\"token punctuation\">(<\/span>route<span class=\"token operator\">:<\/span> Route<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span>\n            <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span>DocumentFragment<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">const<\/span> url <span class=\"token operator\">=<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\"><span class=\"token constant\">URL<\/span><\/span><span class=\"token punctuation\">(<\/span>route<span class=\"token punctuation\">.<\/span><span class=\"token function\">toString<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span> location<span class=\"token punctuation\">.<\/span>href<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Tell the server to only respond with the page's<\/span>\n        <span class=\"token comment\">\/\/ contents, not the full page.<\/span>\n        url<span class=\"token punctuation\">.<\/span>searchParams<span class=\"token punctuation\">.<\/span><span class=\"token function\">set<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'fragment'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">''<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Request the HTML fragment and return it to the<\/span>\n        <span class=\"token comment\">\/\/ base router.<\/span>\n        <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span>url<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">const<\/span> frag <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">return<\/span> frag<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneContent<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ Don't forget to define the custom element!<\/span>\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-router'<\/span><span class=\"token punctuation\">,<\/span> Router<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>This router translates a given route into a network request to the server which\nreturns the HTML fragment to use. Most of this is boilerplate could <em>almost<\/em> be\nentirely done by <code>BaseRouter<\/code>. However, we need this hook in order to provide\nthe <code>?fragment<\/code> query parameter, since <code>BaseRouter<\/code> does not have knowledge of\nthe server or any of its semantics.<\/p>\n<h3 id=\"rendering-the-router\">Rendering the Router<\/h3>\n<p>Now that we have a custom element defining our router, we need to render it in\nthe page. The router requires a <code>&lt;router-outlet&gt;<\/code> element to be somewhere in its\ndescendants where content will be swapped out on navigation. Also, it only\ncaptures navigations from links in its descendants, though they do not <em>have<\/em> to\nbe under the <code>&lt;router-outlet&gt;<\/code>. In practice, this might look like:<\/p>\n<pre><code class=\"language-html\"><span class=\"token doctype\"><span class=\"token punctuation\">&lt;!<\/span><span class=\"token doctype-tag\">DOCTYPE<\/span> <span class=\"token name\">html<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>html<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>head<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/my-router.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>head<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>body<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-router<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token comment\">&lt;!-- Router handles navigation from these links. --><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>nav<\/span><span class=\"token punctuation\">><\/span><\/span>\n                <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n                    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Home<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n                    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/about<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>About<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n                    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>a<\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/contact<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Contact us<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>a<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n                <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>nav<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>main<\/span><span class=\"token punctuation\">><\/span><\/span>\n                <span class=\"token comment\">&lt;!-- `&lt;router-outlet>` gets swapped out\n                    on navigation. --><\/span>\n                <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n                    <span class=\"token comment\">&lt;!-- Don't forget to render the initial\n                        page the user is actually on! --><\/span>\n                    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>h2<\/span><span class=\"token punctuation\">><\/span><\/span>Welcome to the home page!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>h2<\/span><span class=\"token punctuation\">><\/span><\/span>\n                <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>main<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-router<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>body<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>html<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>And with that everything is set up! When the user clicks on a link, it will\nrequest an HTML fragment containing that page&#39;s content, and then swap it into\nthe <code>&lt;router-outlet&gt;<\/code>.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/1-about.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/1-about.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><h2 id=\"demo\">Demo<\/h2>\n<p>You can play with this yourself in a real, running demo below, or <a href=\"https:\/\/html-fragments-routing-demo.dwac.dev\/\" target=\"_blank\">open it in a\nnew tab<\/a>. Bring up DevTools and look at the network tab to see what data\nis being transferred on the initial page load, vs subsequent same-page\nnavigations.<\/p>\n<div class=\"demo\">\n    <aside>\n        <a href=\"https:\/\/html-fragments-routing-demo.dwac.dev\/\" target=\"blank\" rel=\"noopener\" title=\"Open demo in new tab.\">\n            <img src=\"https:\/\/blog.dwac.dev\/res\/img\/open-in-new-tab.svg\" alt=\"Open demo in new tab.\" width=\"64\" height=\"64\" loading=\"lazy\" decoding=\"async\" \/>\n        <\/a>\n    <\/aside>\n    <iframe src=\"https:\/\/html-fragments-routing-demo.dwac.dev\/\" title=\"Demo routing application\" class=\"demo\" loading=\"lazy\"><\/iframe>\n<\/div><p>You can check out the full source code on the <a href=\"https:\/\/github.com\/dgp1130\/html-fragments-routing-demo\/\" target=\"_blank\">GitHub repository<\/a>. Note\nthat the &quot;server-side rendering&quot; logic is actually implemented in a\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Service_Worker_API\/Using_Service_Workers\" target=\"_blank\">service worker<\/a>,\nnot a real server. <a href=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/#service-worker-server\">More on that later.<\/a><\/p>\n<h2 id=\"additional-features\">Additional Features<\/h2>\n<p>A few cool features this router provides:<\/p>\n<h3 id=\"self-contained-components\">Self-contained Components<\/h3>\n<p>HTML fragments already support rich, fully self-contained, and server-side\nrendered web components. This means a route fragment can contain its own\nimplementation which gets dynamically loaded into the page when needed. In this\nexample, we have a counter object which gets its initial state server-side\nrendered (initial value of 5) and can be modified via its buttons. This element\nwas not loaded onto the page previously, but instead is dynamically loaded once\nit is rendered by the router.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/2-counter.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/2-counter.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><h3 id=\"caching\">Caching<\/h3>\n<p>When a same-page navigation occurs, the new route is fetched and displayed while\nthe old route is removed from the DOM. That old route is kept in a cache and\nreused if the user navigates back to that page, whether through the back and\nforward buttons, or clicking the links again. No need to request the route a\nsecond time!<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/3-cache.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/3-cache.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><h3 id=\"maintaining-state\">Maintaining State<\/h3>\n<p>Because web components tend to store their own state and the router caches\npreviously-visited routes, it also means that any state held by those components\nis retained between navigations. For example, the counter remembers the current\ncount even when the user navigates away, and then navigates back. This didn&#39;t\nrequire any special effort to support, either by <code>BaseRouter<\/code> or the\napplication&#39;s <code>Router<\/code> class, it just happened naturally.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/4-cached-counter.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/4-cached-counter.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><h2 id=\"streaming\">Streaming<\/h2>\n<p>Since <a href=\"https:\/\/blog.dwac.dev\/posts\/streaming-html-fragments\/\">I didn't learn my lesson last time<\/a>, I\ndecided to try adding HTML streaming support to this router, how hard could that\nbe?<\/p>\n<p>There are a few important requirements I wanted to cover:<\/p>\n<ol>\n<li>Application router classes should be able to stream HTML fragments.<\/li>\n<li>If the user navigates while content is still streaming, that streaming\nshould continue in the background.<\/li>\n<li>The initial page navigation should be streamed into the router. If the user\nnavigates while that content is still streaming, it should also continue to\nstream that content in that background.<\/li>\n<\/ol>\n<p>The most straightforward case is to render a streaming list of top-level\nelements, so let&#39;s consider a simplified case of two elements streamed with a\ndelay between them.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>1<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #1.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token comment\">&lt;!-- Wait 1 second. --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>2<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #2.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>We&#39;ll also ignore that HTML fragments streaming actually <a href=\"https:\/\/techhub.social\/@develwithoutacause\/109692050991403622\" target=\"_blank\">needs to receive a bit\nof line 2 on the client before it can render line\n1<\/a>, that&#39;s just\nnot important here.<\/p>\n<p>We can implement this API in the router by returning an <code>AsyncGenerator&lt;Node&gt;<\/code>,\nwhich is already the case for the HTML fragments streaming API. This looks like:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> streamDomFragment<span class=\"token punctuation\">,<\/span> BaseRouter<span class=\"token punctuation\">,<\/span> Route <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Router<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">BaseRouter<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/** Implement `route()` as an `AsyncGenerator`. *\/<\/span>\n    <span class=\"token keyword\">protected<\/span> override async <span class=\"token operator\">*<\/span><span class=\"token function\">route<\/span><span class=\"token punctuation\">(<\/span>route<span class=\"token operator\">:<\/span> Route<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span>\n            AsyncGenerator<span class=\"token operator\">&lt;<\/span>Node<span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">const<\/span> url <span class=\"token operator\">=<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\"><span class=\"token constant\">URL<\/span><\/span><span class=\"token punctuation\">(<\/span>route<span class=\"token punctuation\">.<\/span><span class=\"token function\">toString<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span> location<span class=\"token punctuation\">.<\/span>href<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Tell the server to only respond with the page's<\/span>\n        <span class=\"token comment\">\/\/ contents, not the full page.<\/span>\n        url<span class=\"token punctuation\">.<\/span>searchParams<span class=\"token punctuation\">.<\/span><span class=\"token function\">set<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'fragment'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">''<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Use `streamDomFragment()` and yield each node.<\/span>\n        <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span>url<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">for<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> frag <span class=\"token keyword\">of<\/span> <span class=\"token function\">streamDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n            <span class=\"token keyword\">yield<\/span> frag<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneContent<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token punctuation\">}<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ Don't forget to define the custom element!<\/span>\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-router'<\/span><span class=\"token punctuation\">,<\/span> Router<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Things work as expected. Each line streams individually and is displayed\nimmediately. You can even navigate among the other routes and the content will\ncontinue to stream in the background.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/5-streaming.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/5-streaming.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>However, there are two non-obvious problems that arise.<\/p>\n<h3 id=\"mutating-a-streaming-document\">Mutating a Streaming Document<\/h3>\n<p>The previous demo started on the home page and did a same-page navigation to the\nstreaming page. This means the router is requesting the HTML fragment from the\nserver and streaming it into its <code>&lt;router-outlet&gt;<\/code>. This is use case 1.\nmentioned above. However, on my first attempt, this broke down for use case 3.,\nwhere we start on the streaming page and navigate away. Streaming ended up\nappending to the new route!<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/6-streaming-to-wrong-route.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/6-streaming-to-wrong-route.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>The reason for this is that on an initial navigation the browser itself is\ncontrolling the streaming, yet a subsequent navigation to a new route causes the\nrouter to mutate the DOM <em>while<\/em> the browser is still streaming the initial\nnavigation. When the first line streams in, the DOM looks like:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>1<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #1.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Then, the user triggers a navigation, the <code>&lt;div&gt;<\/code> is swapped out and moved into\nthe cache, while the outlet now renders the new page.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>h2<\/span><span class=\"token punctuation\">><\/span><\/span>Hello from the home page!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>h2<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>But the stream from the initial navigation continues. While <code>div#1<\/code> has been\nremoved, the <code>&lt;router-outlet&gt;<\/code> still exists, so the browser will append <code>div#2<\/code>\nto it, even though its content has changed. The HTML parser keeps a reference to\nthe parsed parent node. As child nodes are parsed, they are appended to that\nparent node, regardless of where that parent is or how it has changed since it\nwas parsed. This means you end up with:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>h2<\/span><span class=\"token punctuation\">><\/span><\/span>Hello from the home page!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>h2<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #2.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>We&#39;ve now corrupted the home route with content from streaming route. Our\nself-driving car missed the turn coming in to the neighborhood and is going\nstraight into a river! AAAAAAAH!<\/p>\n<p>Since this streaming behavior is implemented by the browser, the router cannot\ncontrol it. We can&#39;t <em>prevent<\/em> the browser from appending streamed content to\nthe <code>&lt;router-outlet&gt;<\/code> after a navigation. Instead, the solution is to accept\nthat behavior and use it to our advantage.<\/p>\n<p>The original implementation &quot;swapped out&quot; the route content by removing all the\nchild nodes from the <code>&lt;router-outlet&gt;<\/code> element and appending new ones. This is\nhow <code>div#1<\/code> got removed and the <code>&lt;h2&gt;<\/code> tag got added. However, because the\n<code>&lt;router-outlet&gt;<\/code> is unchanged, it continues receiving streamed content from the\ninitial navigation by the browser. We can actually fix this by removing\n<code>&lt;router-outlet&gt;<\/code> along with <code>div#1<\/code> and putting it into the cache. The browser\ndoesn&#39;t actually care that <code>&lt;router-outlet&gt;<\/code> is even attached to the DOM, it\nwill continue to stream new content into it. So if we cache the\n<code>&lt;router-outlet&gt;<\/code> directly, all subsequently streamed content will be appended\nto that cache, not the DOM displayed to the user.<\/p>\n<p>This means we actually need to create a new <code>&lt;router-outlet&gt;<\/code> for the home page.\nIn fact, each route gets its own parent <code>&lt;router-outlet&gt;<\/code> element and these\nnodes are replaced with each other whenever the page changes. That is a bit of a\nstrange way to use an outlet in my opinion and I would naively expect the outlet\nto remain unchanged between routes. However swapping out the outlet allows this\nstreaming behavior to work as expected.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/\/ Wrong! Streamed elements from the old route will continue<\/span>\n<span class=\"token comment\">\/\/ to append to `outlet`!<\/span>\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">swapPageContentBad<\/span><span class=\"token punctuation\">(<\/span>\n        outlet<span class=\"token operator\">:<\/span> Element<span class=\"token punctuation\">,<\/span> newContent<span class=\"token operator\">:<\/span> DocumentFragment<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token keyword\">void<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> cacheFragment <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createDocumentFragment<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    cacheFragment<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span><span class=\"token operator\">...<\/span>outlet<span class=\"token punctuation\">.<\/span>childNodes<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token function\">addToCache<\/span><span class=\"token punctuation\">(<\/span>cacheFragment<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    outlet<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span><span class=\"token operator\">...<\/span>newContent<span class=\"token punctuation\">.<\/span>childNodes<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ Right! `outlet` is moved into the cache. Streamed elements<\/span>\n<span class=\"token comment\">\/\/ from the old route will append to `outlet`, not `newOutlet`!<\/span>\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">swapPageContentGood<\/span><span class=\"token punctuation\">(<\/span>\n        outlet<span class=\"token operator\">:<\/span> Element<span class=\"token punctuation\">,<\/span> newContent<span class=\"token operator\">:<\/span> DocumentFragment<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token keyword\">void<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> newOutlet <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'router-outlet'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    newOutlet<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span><span class=\"token operator\">...<\/span>newContent<span class=\"token punctuation\">.<\/span>childNodes<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    outlet<span class=\"token punctuation\">.<\/span><span class=\"token function\">replaceWith<\/span><span class=\"token punctuation\">(<\/span>newOutlet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token function\">addToCache<\/span><span class=\"token punctuation\">(<\/span>outlet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Ultimately <code>BaseRouter<\/code> will manage this automatically as part of its cache, so\nthere&#39;s nothing you as a user of this router need to worry about here. I just\nthought it was an interesting enough bug to talk about here and I hope it led to\nunderstanding HTML parsing just a little bit better.<\/p>\n<h3 id=\"streaming-a-single-root-element\">Streaming a Single Root Element<\/h3>\n<p>The second problem you do have to worry about. Let&#39;s restructure the streamed\ncontent to be a little more &quot;semantic&quot; and use HTML list elements.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>1<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #1.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token comment\">&lt;!-- Wait 1 second. --><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>2<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #2.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Load this route in the initial navigation and it will stream just fine. But load\na different route first, then navigate to this one, and you&#39;ll see it &quot;stream&quot;\nin one big chunk. That&#39;s not how it&#39;s supposed to work!<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/7-streaming-single-chunk.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/7-streaming-single-chunk.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>The problem here is that the browser and HTML fragments use very different\nstreaming models. The browser on the initial page navigation has no problem\nstreaming an entire document, conceptualized as a single root node with\ndescendants. However, HTML fragments use a different approach based on\n<a href=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/#streaming-complete-chunks\">streaming top-level nodes<\/a>.\nEach node and all its descendants are fully parsed before they are appended to\nthe DOM. This is different from the browser, which will append a node as soon as\nits open tag is parsed and then continue to append to that node as its children\nare parsed.<\/p>\n<p>This incompatibility is an issue here, because there is only one top-level\nelement, the <code>&lt;ul&gt;<\/code> tag! While the fragment can be streamed, it can&#39;t display\nanything until the <code>&lt;\/ul&gt;<\/code> close tag is parsed, meaning we have to wait the full\nsecond before we can even display <code>div#1<\/code>.<\/p>\n<p>We could drop the <code>&lt;ul&gt;<\/code> and just render the <code>&lt;li&gt;<\/code> tags, this way we have\nmultiple top-level nodes to stream.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>1<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #1.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token comment\">&lt;!-- Wait 1 second. --><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>2<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #2.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>But these <code>&lt;li&gt;<\/code> tags will be rendered directly into the <code>&lt;router-outlet&gt;<\/code>\nwithout a <code>&lt;ul&gt;<\/code> parent, which\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTML\/Element\/li\" target=\"_blank\">isn't valid HTML<\/a>.<\/p>\n<p>In my original streaming post, I tackled this problem by rendering the <code>&lt;ul&gt;<\/code>\nand <code>&lt;li&gt;<\/code> tags <a href=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/#conclusion\">client side<\/a>,\nsince <code>streamDomFragment()<\/code> returns an <code>AsyncGenerator<\/code> which can be composed,\nso let&#39;s try that. We&#39;ll let the server return the items in the previous format\nwithout a <code>&lt;ul&gt;<\/code> or <code>&lt;li&gt;<\/code> tag and instead render those directly in the router.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> streamDomFragment<span class=\"token punctuation\">,<\/span> BaseRouter<span class=\"token punctuation\">,<\/span> Route <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/lib\/dom.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Router<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">BaseRouter<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">protected<\/span> override <span class=\"token keyword\">async<\/span> <span class=\"token function\">route<\/span><span class=\"token punctuation\">(<\/span>route<span class=\"token operator\">:<\/span> Route<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span>\n            <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span>DocumentFragment<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">const<\/span> url <span class=\"token operator\">=<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\"><span class=\"token constant\">URL<\/span><\/span><span class=\"token punctuation\">(<\/span>route<span class=\"token punctuation\">.<\/span><span class=\"token function\">toString<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span> location<span class=\"token punctuation\">.<\/span>href<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        url<span class=\"token punctuation\">.<\/span>searchParams<span class=\"token punctuation\">.<\/span><span class=\"token function\">set<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'fragment'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">''<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span>url<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Create a `DocumentFragment` and append a new<\/span>\n        <span class=\"token comment\">\/\/ `&lt;ul>` tag to it.<\/span>\n        <span class=\"token keyword\">const<\/span> frag <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createDocumentFragment<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">const<\/span> list <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'ul'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        frag<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>list<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Stream content in the background and wrap each<\/span>\n        <span class=\"token comment\">\/\/ top-level node in an `&lt;li>` and append it to the<\/span>\n        <span class=\"token comment\">\/\/ `&lt;ul>` element.<\/span>\n        <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n            <span class=\"token keyword\">for<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> node <span class=\"token keyword\">of<\/span> <span class=\"token function\">streamDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n                <span class=\"token keyword\">const<\/span> listItem <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'li'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n                listItem<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>node<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneContent<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n                list<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>listItem<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n            <span class=\"token punctuation\">}<\/span>\n        <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Return the fragment with only its initial content<\/span>\n        <span class=\"token comment\">\/\/ for now. As more streams in, we'll asynchronously<\/span>\n        <span class=\"token comment\">\/\/ update the fragment via the above IIFE.<\/span>\n        <span class=\"token keyword\">return<\/span> frag<span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-router'<\/span><span class=\"token punctuation\">,<\/span> Router<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>This does stream as expected. Open the home page and navigate to the streaming\nroute and the <code>&lt;ul&gt;<\/code> element is created immediately, while <code>&lt;li&gt;<\/code> tags are added\nas the content is streamed in. However, refresh on the streaming page you&#39;ll\nsee that the <code>&lt;ul&gt;<\/code> and <code>&lt;li&gt;<\/code> are completely missing!<\/p>\n<pre><code class=\"language-html\"><span class=\"token doctype\"><span class=\"token punctuation\">&lt;!<\/span><span class=\"token doctype-tag\">DOCTYPE<\/span> <span class=\"token name\">html<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>html<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>body<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token comment\">&lt;!-- No `&lt;ul>` or `&lt;li>` tags! --><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>1<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #1.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>2<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello from line #2.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>router-outlet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>body<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>html<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Since we&#39;re rendering those elements in the router on the client, the initial\npage load won&#39;t have them, how inaccessible of us!<\/p>\n<p>The core reason for this discrepancy is that HTML fragments doesn&#39;t stream the\nsame way a browser does natively. Browsers stream a complete HTML document, a\nhierarchy of nodes. Meanwhile HTML fragments stream a list of independent nodes.\nRendering the <code>&lt;ul&gt;<\/code> tag on the server breaks HTML fragments, but <em>not<\/em>\nrendering the <code>&lt;ul&gt;<\/code> tag breaks browser streaming on the initial navigation.<\/p>\n<p>The only way to resolve this discrepancy is to render the two cases differently.\nWe need the <code>&lt;ul&gt;<\/code> tag for the initial render of a streaming route, but omit the\ntag for a fragment render of the same route. The sever can do this based on the\n<code>?fragment<\/code> query parameter:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">function<\/span> <span class=\"token function\">serveStreamingPage<\/span><span class=\"token punctuation\">(<\/span>request<span class=\"token operator\">:<\/span> Request<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Response <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> isRequestingFragment <span class=\"token operator\">=<\/span>\n        <span class=\"token keyword\">new<\/span> <span class=\"token class-name\"><span class=\"token constant\">URL<\/span><\/span><span class=\"token punctuation\">(<\/span>request<span class=\"token punctuation\">.<\/span>url<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span>searchParams<span class=\"token punctuation\">.<\/span><span class=\"token function\">has<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'fragment'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>isRequestingFragment<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ For fragment requests, just stream the `&lt;div>` tags.<\/span>\n        <span class=\"token comment\">\/\/ `Response` actually requires a `ReadableStream`,<\/span>\n        <span class=\"token comment\">\/\/ not an `AsyncGenerator`, but please forgive my sins.<\/span>\n        <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Response<\/span><span class=\"token punctuation\">(<\/span><span class=\"token function\">streamItems<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">else<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ For full page requests, wrap the `&lt;div>` tags in<\/span>\n        <span class=\"token comment\">\/\/ the `&lt;ul>` and `&lt;li>` tags.<\/span>\n        <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Response<\/span><span class=\"token punctuation\">(<\/span>\n            <span class=\"token function\">renderPageFrame<\/span><span class=\"token punctuation\">(<\/span><span class=\"token function\">renderList<\/span><span class=\"token punctuation\">(<\/span><span class=\"token function\">streamItems<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">async<\/span> <span class=\"token keyword\">function<\/span><span class=\"token operator\">*<\/span> <span class=\"token function\">streamItems<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> AsyncGenerator<span class=\"token operator\">&lt;<\/span><span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">yield<\/span> <span class=\"token string\">'&lt;div id=\"1\">Hello from line #1.&lt;\/div>'<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">await<\/span> <span class=\"token function\">timeout<\/span><span class=\"token punctuation\">(<\/span><span class=\"token number\">1_000<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">yield<\/span> <span class=\"token string\">'&lt;div id=\"2\">Hello from line #2.&lt;\/div>'<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">async<\/span> <span class=\"token keyword\">function<\/span><span class=\"token operator\">*<\/span> <span class=\"token function\">renderList<\/span><span class=\"token punctuation\">(<\/span>items<span class=\"token operator\">:<\/span> AsyncGenerator<span class=\"token operator\">&lt;<\/span><span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span>\n        AsyncGenerator<span class=\"token operator\">&lt;<\/span><span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">yield<\/span> <span class=\"token string\">'&lt;ul>'<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">for<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> item <span class=\"token keyword\">of<\/span> items<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">yield<\/span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">&lt;li><\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>item<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token string\">&lt;\/li><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n    <span class=\"token keyword\">yield<\/span> <span class=\"token string\">'&lt;\/ul>'<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>In combination with the client-side list rendering in the router, this does\nactually work in both cases. All the streaming requirements are satisfied.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/8-streaming-list.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"1080\" controls=\"\" style=\"aspect-ratio: 1920 \/ 1080; max-height: 1080px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/demos\/8-streaming-list.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>The downside of this is that it duplicates list rendering in two places which\ncan easily fall out of sync and result in very hard to find bugs. It&#39;s also two\ndifferent code paths to test, further adding to the complexity.<\/p>\n<h3 id=\"router-loading-timing\">Router Loading Timing<\/h3>\n<p>One other very minor caveat is that in order to meet requirement 3. (initial\npage load followed by a navigation should continue streaming in the background),\nwe need to make sure the router JavaScript is not blocked on rendering. For\nexample consider the following document:<\/p>\n<pre><code class=\"language-html\"><span class=\"token doctype\"><span class=\"token punctuation\">&lt;!<\/span><span class=\"token doctype-tag\">DOCTYPE<\/span> <span class=\"token name\">html<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>html<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>head<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/router.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>head<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>body<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-router<\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token comment\">&lt;!-- ... --><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-router<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>body<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>html<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>This has a bug, or at least a confusing behavior. If we load this page initially\nand then click a link to navigate while streaming, then navigate back to the\ninitial page, the stream restarts. It&#39;s not preserved!<\/p>\n<p>The reason for this is actually <code>type=&quot;module&quot;<\/code>. ES module scripts are\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTML\/Element\/script#attr-defer\" target=\"_blank\">implicitly deferred<\/a>.\nDeferred scripts execute after the full document has been downloaded and parsed,\nmeaning it won&#39;t execute until <em>after<\/em> the page is fully loaded. By clicking a\nlink during streaming, the user is triggering a navigation before the <code>Router<\/code>\nclass has been defined or the <code>my-router<\/code> custom element has been upgraded. As a\nresult, the timeline of events looks like:<\/p>\n<ol>\n<li>User navigates to <code>\/streaming<\/code>.<\/li>\n<li>Browser begins downloading the page and streaming it into the document.<\/li>\n<li>Browser sees <code>&lt;script src=&quot;\/router.js&quot; type=&quot;module&quot;&gt;&lt;\/script&gt;<\/code>, defers the\nscript and does not execute it.<\/li>\n<li>User clicks a link to <code>\/home<\/code>.<\/li>\n<li><code>my-router<\/code> has not been defined yet, so the browser handles the navigation.<\/li>\n<li>Browser navigates to <code>\/home<\/code> and makes a full page request to the server.<\/li>\n<li>Browser sees a new <code>&lt;script src=&quot;\/router.js&quot; type=&quot;module&quot;&gt;&lt;\/script&gt;<\/code>,\ndefers the script and does not execute it.<\/li>\n<li>The <code>\/home<\/code> page finishes downloading, deferred scripts are executed.<\/li>\n<li><code>\/router.js<\/code> is executed and <code>my-router<\/code> is defined.<\/li>\n<li>User clicks a link back to <code>\/streaming<\/code>.<\/li>\n<li><code>my-router<\/code> intercepts the click and performs a same-page navigation to\n<code>\/streaming<\/code>.<\/li>\n<li><code>\/streaming<\/code> is not in the fragment cache, so a new HTML fragment request is\nsent to the server, restarting the stream.<\/li>\n<\/ol>\n<p>Ironically this is exactly the right fallback behavior to use in cases where the\nrouter is failing or slow to load and results in the ideal user experience. Most\nusers likely wouldn&#39;t notice that the stream was lost, and if the original route\ndidn&#39;t use streaming, it wouldn&#39;t really be observable to the user at all. There\nwould only be a small performance hit because the user has to re-download the\nwhole page, rather than just the new route. Any user data held in page memory\nwould be lost, but in such a situation the router hasn&#39;t loaded yet anyways, so\nthe user probably hasn&#39;t input any information which could be lost by doing a\nhard navigation.<\/p>\n<p>That said, we would still want to load the router as soon as it can for\nstreaming use cases. To fix this behavior we need to avoid blocking <code>\/router.js<\/code>\non fully parsing the document. We can do this by adding\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTML\/Element\/script#attr-async\" target=\"_blank\"><code>async<\/code><\/a>\nto the script:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/router.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>I&#39;d known about this attribute for a while but don&#39;t think I really understood\nit until now. <code>defer<\/code>, and by extension <code>type=&quot;module&quot;<\/code>, pushes out script\nexecution until the page is fully parsed, meaning they will never execute on a\ndocument while it is still streaming. In practice, I think this is usually what\nyou want. It&#39;s good for the user and also means that as a developer you don&#39;t\nneed to worry about cases where the document isn&#39;t fully downloaded (no need to\nlisten for <code>DOMContentLoaded<\/code>).<\/p>\n<p><code>async<\/code> means that the script is executed <em>as soon as it is downloaded<\/em>. An\n<code>async<\/code> script does <em>not<\/em> block HTML parsing like a plain <code>&lt;script&gt;<\/code> tag does,\nbut also HTML parsing does <em>not<\/em> block <code>async<\/code> scripts like it blocks deferred\nscripts. Marking the router <code>async<\/code> means that it will execute even before the\npage is fully downloaded if it happens to download first, meaning it can catch\nevents which happen during streaming.<\/p>\n<p>I think what confused me about <code>async<\/code> is that it actually makes deferred\nscripts execute <em>sooner<\/em>, but makes non-deferred scripts execute <em>later<\/em>. Either\nof these outcomes would be easy to understand in isolation, but the conflicting\ntiming effects from the same attribute make it a bit harder to understand as a\nsingular concept. Hopefully this helps explain when and where you would want to\nuse <code>async<\/code>.<\/p>\n<p>Alternatively, if you&#39;re not using native ES modules you can drop\n<code>type=&quot;module&quot;<\/code> and make the <code>&lt;script&gt;<\/code> block the parser to force <code>my-router<\/code>\nto load first. Although that would slow down parsing and degrade the user\nexperience causing <a href=\"https:\/\/infrequently.org\/\" target=\"_blank\">Alex Russell<\/a> to inject 50MBs of\nJavaScript into your dreams, so maybe <em>don&#39;t<\/em> take that approach. \ud83d\ude09<\/p>\n<p>I think that&#39;s enough about streaming. The takeaway is that it works, it just\nhas some nuances to keep in mind.<\/p>\n<h2 id=\"limitations\">Limitations<\/h2>\n<p>Beyond that, it is important to remember that this router just a\nproof-of-concept and is not fully-featured. There are plenty of features this\nrouter would need to be viable in scalable production application:<\/p>\n<ul>\n<li>The fragment cache currently grows unbounded on each navigation. If the user\nnavigates through a large number of product pages, they would continually\ngrow the cache until their browser ran out of memory.<\/li>\n<li>Fragments requests are never canceled and instead work under the assumption\nthat they should download in the background in case the user wants to return\nto that route. Ideally there would be some way to decide when to cancel the\nrequest and restart it on a return navigation.<\/li>\n<li>Lots of other standard router features aren&#39;t included, such as:<ul>\n<li>Route guards.<\/li>\n<li>404 routes.<\/li>\n<li>Route redirects.<\/li>\n<\/ul>\n<\/li>\n<li>Currently the router captures all descendent link clicks to trigger\nsame-page navigations. I doubt this is the right mechanism, but it was good\nenough for this demo.<\/li>\n<li>All the routing logic is centralized directly in the router. There is no\ndirectly supported way to split this logic per-route.<\/li>\n<\/ul>\n<p>Hopefully this is an interesting demo, but there is a reason I didn&#39;t publish\nthis as an immediately usable NPM package. So maybe leave it as just a demo for\nnow.<\/p>\n<p>All that said, thank you for joining me on this journey and I hope you learned\nsomething along the way. Check out the <a href=\"https:\/\/html-fragments-routing-demo.dwac.dev\/\" target=\"_blank\">running demo<\/a> to see everything in\naction or look at the <a href=\"https:\/\/github.com\/dgp1130\/html-fragments-routing-demo\/\" target=\"_blank\">GitHub repository<\/a> for the source code.<\/p>\n<h2 id=\"service-worker-server\">Service Worker Server<\/h2>\n<p><strong>Bonus mini blog post:<\/strong> While developing this demo, I wanted to ship a\ndeployed version for readers to play around with, so they wouldn&#39;t have to clone\nthe repository and run a local build. Unfortunately, the demo is all about\nserver-side rendering, and I was too cheap to pay for a real, everlasting server\nto run a demo for a single blog post. Sorry, you&#39;re just not worth a $5\/month\ncharge for the rest of my life.<\/p>\n<p>So instead, I decided to host the server <em>inside a\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Service_Worker_API\/Using_Service_Workers\" target=\"_blank\">service worker<\/a><\/em>.\nThis means the initial page load downloads a static page which serves the sole\npurpose of registering a service worker, and then triggers a refresh. That\nrefresh goes to the service worker, which applies all the server-side rendering\nlogic for the real application. It&#39;s like SSR, but everything happens client\nside. This particular server implementation is also aware of the <code>?fragment<\/code>\nquery parameter, and implements it for you.<\/p>\n<p><a href=\"https:\/\/github.com\/dgp1130\/html-fragments-routing-demo\/blob\/blog-post\/src\/app-server.ts\" target=\"_blank\">Building a server looks like:<\/a><\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> ServiceWorkerServer <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/sw-server.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/** Render the full page frame around the given page content. *\/<\/span>\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">renderFrame<\/span><span class=\"token punctuation\">(<\/span>_req<span class=\"token operator\">:<\/span> Request<span class=\"token punctuation\">,<\/span> content<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\n&lt;!DOCTYPE html>\n&lt;html>\n    &lt;head>\n        &lt;script src=\"\/my-router.js\" type=\"module\" async>&lt;\/script>\n    &lt;\/head>\n    &lt;body>\n        &lt;my-router>\n            &lt;nav>...&lt;\/nav>\n            &lt;main>\n                &lt;router-outlet><\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>content<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token string\">&lt;\/router-outlet>\n            &lt;\/main>\n        &lt;\/my-router>\n    &lt;\/body>\n&lt;\/html>\n    <\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">trim<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">renderHome<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token string\">'&lt;h2>Hello from the home page!&lt;\/h2>'<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">renderAbout<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">&lt;h2>Hello from the about page!&lt;\/h2><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/**\n * Build the application server from all routes. Automatically\n * handles `?fragment` and calls `renderFrame` appropriately.\n *\/<\/span>\n<span class=\"token keyword\">const<\/span> server <span class=\"token operator\">=<\/span> ServiceWorkerServer<span class=\"token punctuation\">.<\/span><span class=\"token function\">fromRoutes<\/span><span class=\"token punctuation\">(<\/span>\n    renderFrame<span class=\"token punctuation\">,<\/span>\n    <span class=\"token comment\">\/\/ Map of routes. Any requests not in these routes are<\/span>\n    <span class=\"token comment\">\/\/ proxied to the actual backend. Meaning static files<\/span>\n    <span class=\"token comment\">\/\/ like JS, CSS, or images still load as expected.<\/span>\n    <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Map<\/span><span class=\"token punctuation\">(<\/span>Object<span class=\"token punctuation\">.<\/span><span class=\"token function\">entries<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n        <span class=\"token string-property property\">'\/'<\/span><span class=\"token operator\">:<\/span> renderHome<span class=\"token punctuation\">,<\/span>\n        <span class=\"token string-property property\">'\/about\/'<\/span><span class=\"token operator\">:<\/span> renderAbout<span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ Proxy all outgoing browser requests through the server.<\/span>\nself<span class=\"token punctuation\">.<\/span><span class=\"token function\">addEventListener<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'fetch'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">(<\/span>event<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    event<span class=\"token punctuation\">.<\/span><span class=\"token function\">respondWith<\/span><span class=\"token punctuation\">(<\/span>server<span class=\"token punctuation\">.<\/span><span class=\"token function\">serve<\/span><span class=\"token punctuation\">(<\/span>event<span class=\"token punctuation\">.<\/span>request<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>There&#39;s also the small\n<a href=\"https:\/\/github.com\/dgp1130\/html-fragments-routing-demo\/blob\/blog-post\/src\/index.ts\" target=\"_blank\">bootstrap script<\/a>\nwhich is needed to register the service worker and reload the page. This exists\nin a static HTML page which is hosted on a CDN.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">await<\/span> navigator<span class=\"token punctuation\">.<\/span>serviceWorker<span class=\"token punctuation\">.<\/span><span class=\"token function\">register<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/service-worker.js'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">{<\/span> type<span class=\"token operator\">:<\/span> <span class=\"token string\">'module'<\/span> <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\nlocation<span class=\"token punctuation\">.<\/span><span class=\"token function\">reload<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>You can observe this in the network tab, especially if you uninstall the service\nworker or set it to automatically update on reload. For the purposes of this\ndemo you can mostly ignore it, and just pretend the service worker is a real\nserver.<\/p>\n<p>I don&#39;t see a lot of value in SSR-ing from a service worker outside of\nself-contained SSR demos. If I find myself using it a lot, maybe I&#39;ll make a\nreal library for it. Although thinking about it, <a href=\"https:\/\/tweets.dwac.dev\/1571759598910214144\/\" target=\"_blank\">shipping a service worker in a\nweb bundle could lead to a truly serverless web\napplication<\/a>... No, nope, not\ngonna happen. I don&#39;t have time to follow that rabbit hole right now. There&#39;s\nbeen too many divergences already and we gotta wrap this up.<\/p>\n<p>The point is that by <del>ab<\/del>using a service worker like this, I can effectively\nhost a server-side rendered application on a static CDN. And since Netlify gives\nfree hosting for static sites, that&#39;s $5\/month I no longer have to pay! Now if\nyou&#39;ll excuse me, I&#39;ll be off enjoying my $5.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 640 \/ 360; max-height: 360px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"640\" height=\"360\" class=\"gif\" style=\"aspect-ratio: 640 \/ 360; max-height: 360px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/make-it-rain.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"640\" height=\"360\" class=\"gif\" style=\"aspect-ratio: 640 \/ 360; max-height: 360px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments-routing\/make-it-rain.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy>"},{"title":"Leaving Twitter","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/twitter\/"}},"updated":"2023-01-08T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/twitter\/","content":"<h1 id=\"leaving-twitter\">Leaving Twitter<\/h1>\n<time datetime=\"2023-01-08T19:00:00.000Z\" class=\"timestamp\">January 8, 2023<\/time><p>If you&#39;re reading this at the time of posting, you know exactly what I&#39;m going\nto say and why. If you&#39;re reading from the future some context might be helpful.\n(Also, has Linux taken over yet? It&#39;s the year of the Linux desktop now right?)<\/p>\n<p>Elon Musk took over Twitter and has put the company into a tailspin to put\nthings charitably. In his short tenure there he has managed to:<\/p>\n<ul>\n<li>Bring in external devs to do forced code reviews of the entire company to\ngauge performance.<\/li>\n<li>Fire at least half the staff.<\/li>\n<li>Cause several outages of varying severity.<\/li>\n<li>Promote &quot;free speech&quot; by banning Twitter accounts which he personally\ndisagrees with.<\/li>\n<li>Make major policy decisions via Twitter poll.<\/li>\n<li>Disband content moderation council and lie about it.<\/li>\n<li>Break Twitter verified labels multiple times.<\/li>\n<li>Publicly harass employees.<\/li>\n<li>Reinstate numerous banned accounts, notably including Donald Trump.<\/li>\n<\/ul>\n<h2 id=\"the-technical-stuff\">The Technical Stuff<\/h2>\n<p>Elon seems to have absolutely no idea what kind of company he bought and what to\ndo with it. I would laugh at all this if it weren&#39;t so depressing. There&#39;s a lot\nof stupid decisions he&#39;s made, but I think it all comes down to the fact that he\ndoesn&#39;t understand what a social media company is. He looks at everything\nthrough the realm of an engineer trying to solve a <em>technical<\/em> problem (how do\nwe serve tweets efficiently), not as a leader trying to solve a <em>social<\/em> problem\n(how do we incentivize people to have positive human interactions).<\/p>\n<p>Twitter&#39;s source code and its infrastructure is the easy part. &quot;Easy&quot; should be\nread in <em>gigantic<\/em> air quotes of course. Scaling anything to support hundreds of\nmillions of users is absolutely difficult, and Twitter is no exception. However\nas a social media company, the focus of its leader needs to be on making the\nplatform accessible, supporting disadvantaged users, and defining moderation\npolicies. When building a social platform, the &quot;platform&quot; is the straightforward\npart, it&#39;s the &quot;social&quot; where things get complicated.<\/p>\n<p><a href=\"https:\/\/twitter.com\/reckless\" target=\"_blank\">Nilay Patel<\/a> put it best in\n<a href=\"https:\/\/www.theverge.com\/2022\/10\/28\/23428132\/elon-musk-twitter-acquisition-problems-speech-moderation\" target=\"_blank\">Welcome to hell, Elon<\/a>\n(emphasis mine):<\/p>\n<blockquote>\n<p>The essential truth of every social network is that <strong>the product is content\nmoderation<\/strong><\/p>\n<\/blockquote>\n<p>Say what you will about Jack Dorsey&#39;s Twitter, at least he seemed to understand\nthis key point. Twitter leadership historically focused a lot of attention on\ndefining content policies, empowering moderators and building a moderation\ncouncil, handling abuse, supporting disadvantaged users, etc. It was never\nperfect for sure and Twitter certainly made missteps along the way. However it\nalways came across as at least <em>trying<\/em> to do the right thing. Twitter always\nrecognized that content moderation is both <em>important<\/em> and <em>nuanced<\/em>, two things\nElon still fails to grasp.<\/p>\n<p>Elon loves to tout &quot;free speech&quot; as the motivator for everything that he does.\nMost of his reasoning sounds great on the surface to me, an affluent caucasian\nheterosexual male. But of course, my experience in social media and the\nprivilege I have as someone who never once had to block someone yields a very\ndifferent perspective than many other Twitter users. I at least understand that\nnot everyone has my experience. I can see people who <em>do<\/em> have to block others\nand the harm which motivates them to do so. This is where policies like\nmass-unbanning or &quot;anything that&#39;s legal is allowed&quot; cause very real harm for\nusers.\n<a href=\"https:\/\/www.techdirt.com\/2022\/11\/02\/hey-elon-let-me-help-you-speed-run-the-content-moderation-learning-curve\/\" target=\"_blank\">Mike Masnick's content moderation speedrun article<\/a>\narticle does a much better job than I can of breaking down how complicated &quot;free\nspeech&quot; really is and demonstrates a nuanced understanding of the topic Elon\nclearly lacks.<\/p>\n<p>It&#39;s worth remembering that Twitter has had financial problems long before Elon\ntook over. Twitter has never really been sustainable and was always dependent on\ninvestors. Jack Dorsey himself has\n<a href=\"https:\/\/twitter.com\/jack\/status\/1562861302242226178\" target=\"_blank\">publicly regretted<\/a> that\nTwitter became a company in the first place, so it&#39;s quite possible it was\ndoomed the moment it incorporated. Despite that, it is still absolutely fair to\ncriticize Elon for buying the company seemingly as a joke without any coherent\nstrategy for what to do with it. So far, Elon&#39;s solution seems to be to lay off\nhalf the staff, drive off most of his advertisers, and break verified branding\nso people pay $8 to fix it. Elon may not have created these problems, but they\nare the problems he adopted when he purchased the company. Yet he seems to have\nno idea what to do about them and is flying by the seat of his tweets.<\/p>\n<p>Also, this might seem petty given that I don&#39;t work for Twitter, but Elon just\nseems like the world&#39;s worst boss. Mass layoffs with seemingly no compassion for\naffected employees, making major policy decisions by Twitter poll, bringing in\nTesla employees to code review Twitter employees, changing his mind on an hourly\nbasis, publicly arguing with employees about infrastructure, etc. I usually\ndon&#39;t care too much about big tech executives. As a current Google employee, I\ncan say that decisions Sundar Pichai makes are so far removed from what I deal\nwith on a day-to-day basis as to be near meaningless. I feel similarly about\nmost major executives and I don&#39;t typically judge a company or my desire to work\nthere based on its C-level execs. But Elon is absolutely a CEO I would <em>never<\/em>\nwant to work for (maybe Zuckerburg too).\n<a href=\"https:\/\/mastodon.social\/@rodhilton\/109572674700288958\" target=\"_blank\">Rod Hilton put it best<\/a>:<\/p>\n<blockquote>\n<p>He talked about electric cars. I don&#39;t know anything about cars, so when\npeople said he was a genius I figured he must be a genius.<\/p>\n<p>Then he talked about rockets. I don&#39;t know anything about rockets, so when\npeople said he was a genius I figured he must be a genius.<\/p>\n<p>Now he talks about software. I happen to know a lot about software &amp; Elon Musk\nis saying the stupidest shit I&#39;ve ever heard anyone say, so when people say he&#39;s\na genius I figure I should stay the hell away from his cars and rockets.<\/p>\n<\/blockquote>\n<p>Even beyond these subjective philosophical concerns, Elon&#39;s takeover has led to\nvery real and practical concerns about security and privacy. Can Twitter&#39;s users\ntrust the company to secure their data and keep their information private given\nthe massive amount of layoffs, churn, and general turmoil at the company? Does\ncurrent Twitter feel like a safe and secure place for your information? Does\nElon seem like the kind of guy who would encourage developers to take the time\nto properly security review the PR which breaks the verified checkmark?<\/p>\n<h2 id=\"the-political-stuff\">The Political Stuff<\/h2>\n<p>I typically try to avoid talking too much about politics publicly, mainly for my\nown mental health. However I personally have a red line about sharing a platform\nwith the... <em>everything...<\/em> that Donald Trump represents. In particular, as of\ntoday Trump has faced little to no personal accountability for his hundreds (?)\nof scandals and particularly for attempting to <em>overthrow the government<\/em>. As of\ntoday he is yet to be indicted for anything and while his political power has\ncertainly weakened (largely because of his bans from social media IMHO), he is\nstill a very real contender for the 2024 presidential race.<\/p>\n<p>Being kicked off social media was arguably the biggest consequence he has faced\nup until now and Twitter arguably led that effort in the immediate aftermath of\nJanuary 6th. Rolling that back and letting him back onto the platform feels like\nit is reverting the smallest shred of accountability he has faced up to this\npoint.<\/p>\n<p>As of today, Trump has not actually activated the account, claiming he would\nrather use his own platform &quot;Truth Social&quot;. Personally I can&#39;t see that site\never getting the kind of reach he would demand and sooner or later he&#39;ll come\nback to the bird, but that&#39;s just my speculation. Whether he returns or not is\nirrelevant to the fact he has regained what little privilege was taken from him.<\/p>\n<p>I could go on, but I really don&#39;t want to and this is why I try to avoid\npolitics. The key point is that I personally refuse to share a platform with\nDonald Trump (whether he participates or not), and inviting him back to the\nplatform was when I knew I no longer wanted to be a part of Elon&#39;s Twitter.<\/p>\n<h2 id=\"whats-next\">What&#39;s Next?<\/h2>\n<p>Well if it wasn&#39;t obvious from the rest of this post, I&#39;m deactivating my\nTwitter account. This is a decision from a number of root causes stemming from\nElon&#39;s takeover. It started with bringing Trump back onto the platform, to being\na terrible boss in every way, to no longer trusting the company with my\nsecurity.<\/p>\n<p>I&#39;m not really much of a social media person, and Twitter for me was always\nabout the community I wanted to be a part of. I created my account shortly after\njoining the Angular team as I wanted to be more involved in open source\nsoftware, particularly web developers. Twitter was always just a means to that\nend, and I&#39;m more interested in following that community wherever it goes.<\/p>\n<p>Over the past few months, I&#39;ve seen a bunch of people in this community\nmigrating to <a href=\"https:\/\/joinmastodon.org\/\" target=\"_blank\">Mastodon<\/a>, whether fully or partially,\nand I made the jump myself to\n<a href=\"https:\/\/techhub.social\/@develwithoutacause\" target=\"_blank\">@develwithoutacause@techhub.social<\/a>.\nUltimately moving communities between platforms is very messy. It&#39;s a slow\nprocess, different people are looking for different things, and\n<a href=\"https:\/\/xkcd.com\/1095\/\" target=\"_blank\">communities are infinitely fractal<\/a>. However I&#39;ve seen\nenough of my follows moving to Mastodon and had enough positive experiences with\nthe platform to see a healthy and thriving community there for anyone interested\nin joining.<\/p>\n<p>While the user experience is very similar to Twitter, the culture is noticeably\ndifferent. People tend to be more active and engaged, boost interesting content\ndue to the lack of ranking algorithms, and be less focused on a &quot;topic of the\nday about dunking on the stupid person doing a stupid thing.&quot; While the\ncommunity is definitely smaller, I still get about the same amount of engagement\non Mastodon as I do on Twitter, and generally higher quality in my opinion.\nAlso, there&#39;s a solid number of people I previously followed on Twitter whom\nI&#39;m pretty sure did not follow me back, but have decided to follow me on\nMastodon. I&#39;m not sure how much of this is just people becoming acquainted with\nthe new platform and how much is a result of distinct cultural differences.\nWe&#39;ll have to see how things shake out in the future.<\/p>\n<h3 id=\"so-is-mastodon-the-future\">So is Mastodon the future?<\/h3>\n<p>Ultimately I&#39;m joining Mastodon in order to stay connected with the open source\nand web development communities. While Mastodon does meet my needs, I do have a\nnumber of concerns as to the long term health of the ecosystem.<\/p>\n<p>First, I don&#39;t see a sustainable financial model for maintaining Mastodon\nservers right now. Twitter solved this problem mainly with advertisements, but\nMastodon explicitly rejects ads and everything is largely self-funded or handled\nvia donations. This can be good enough for hobbyist instances or small\ncommunities, but is far off from the hundreds of millions of users Twitter was\nsuccessfully serving. This problem ultimately reduces to the more general\nproblem of open source sustainability, which is still a major challenge in the\nindustry with no clear answer.<\/p>\n<p>Donations are great, but have yet to take off as a sustainable mainstream\nbusiness model on the internet, and I don&#39;t see that changing in the immediate\nfuture. Maybe it&#39;s because I work for an advertising company, but personally I&#39;d\nbe totally fine if a server showed ads and that made enough revenue to keep the\nservice free. The current state of ad-funded social networks serves as an\nexistence proof that many users are comfortable with that as an idea. However, I\nexpect that the OSS community behind Mastodon would likely have strong\nphilosophical objections about such an approach. I can absolutely see the\nad-based monetization model weaken as the the legal landscape around user\nprivacy evolves, so maybe online culture will slowly shift and Mastodon is\nactually ahead of the curve. Hopefully the diversity of servers and people in\nthis space will find the right sustainability model for them, but I&#39;ve yet to\nsee anything which really seems like a clear success. All that said, please toss\na coin to your server admins.<\/p>\n<p>Second, Mastodon seems to have a contradiction between &quot;small tight-knit\ncommunity&quot; and &quot;global social network&quot;. This is best exemplified by the way\nsevers work. The server you pick is really important because it&#39;s the community\nyou&#39;re associating with, the moderation policy you&#39;re agreeing to, the\ninfrastructure you want to see sustainable, and the maintainers you&#39;re trusting\nwith your security and privacy. But also the server is completely <em>unimportant<\/em>\nbecause you can change it at any time, see content from any other server, or\neven host your own server with your own rules.<\/p>\n<p>There&#39;s a fundamental contradiction here about what the server <em>represents<\/em> to\nits community. From a practical perspective I personally feel like the server is\nmainly the infrastructure serving my traffic and also the domain attached to my\nMastodon handle. I can&#39;t associate a name or face with my server admin because I\nsee Mastodon as a &quot;global social network&quot;, but there are absolutely others who\ndo know their server admins and have direct conversations with them about\nmoderation decisions and other topics of the day.<\/p>\n<p>Compare this to Slack, Discord, or a subreddit where the community tends to be\ntightly focused on a particular topic and have certain expectations about the\nmembers of that community. I can go to the DragonBall FighterZ subreddit and\npost <code>5L5L2M5M JC 5L5M5L2H SD 5L5M5L2H JC 5LL236L 236MH<\/code> and people actually\nknow what I&#39;m talking about. Meanwhile the same thing in programming subreddit\nlooks like a language made up from scratch for code golfing.<\/p>\n<p>Twitter is at the opposite end of the spectrum where communities are much more\nambiguous and focused on individuals rather than well-defined communities. Users\nfollow other users directly and hashtags only loosely link specific topics or\nideas.<\/p>\n<p>Exactly where Mastodon fits into this spectrum is still unclear to me. That&#39;s\nnot necessarily fatal or even a bad thing. Maybe we can find the best of both\nworlds. Or maybe different users will have different expectations of each other\nand lead to unproductive conflict. I don&#39;t really know, it&#39;s just an aspect\nwhich has confused me and I don&#39;t think I have a good answer for it right now.<\/p>\n<p>Thirdly, I don&#39;t really see clear user-facing benefits to decentralization in\nMastodon. This is a bigger problem with the blockchain community, but that&#39;s a\nwhole separate blog post. I have a pet peeve about &quot;decentralization&quot; as a\nselling point. <strong>Decentralization is not a feature. Decentralization is an\narchitectural choice.<\/strong> Don&#39;t sell me on how decentralized your product is, sell\nme on the <em>features<\/em> which are enabled by your decentralized architecture that\nmake you better than centralized alternatives. &quot;You can pick a server with\nmoderation policies you like&quot; or &quot;you can own your server and be protected from\na power-hungry admin&quot; are features enabled by decentralization, sell me on\nthose, not the mythical &quot;decentralization&quot; bullet point.<\/p>\n<p>Does decentralization allow Mastodon to provide more value for users than other\nsocial networks? If there was ever a reason to choose a decentralized social\nnetwork, Twitter&#39;s implosion was it. &quot;Leave a crazed power-hungry admin&quot; is\nquite literally the exact reason I&#39;m leaving Twitter. Even this blog was heavily\ninspired by\n<a href=\"https:\/\/www.hanselman.com\/blog\/your-words-are-wasted\" target=\"_blank\">Scott Hanselman's \"own your words\" mantra<\/a>,\nsomething more relevant now than ever. However, I&#39;m not the average user and the\nproduct designer in me still sees more complexity and downsides for the typical\nuser in a decentralized system like Mastodon than a centralized one like\nTwitter. I&#39;m just personally not convinced this is a significant improvement in\nMastodon&#39;s favor.<\/p>\n<p>I don&#39;t want to be too negative about all this, there&#39;s a lot to like about\nMastodon. I love the culture of adding alt text to everything, I could see\nmyself running a server for my own identity, and the community has been overall\nquite welcoming.<\/p>\n<p>I could go on baselessly opining about Mastodon, but this post is already way\nlonger than I expected and I&#39;m still learning myself. So instead, let&#39;s wrap\nthis up by baselessly opining about Twitter!<\/p>\n<h3 id=\"is-twitters-dead\">Is Twitter&#39;s Dead?<\/h3>\n<p>Despite Elon&#39;s best efforts to the contrary, I do think Twitter will stick\naround for quite a while. It&#39;s simply too big and too ingrained in the current\ninternet culture to disappear overnight. The vast majority of brands,\ncelebrities, public figures, and influencers will weather the storm and keep on\ntweeting without all that much change.<\/p>\n<p>Even MySpace still exists today. But like MySpace, social media networks tend\nnot to die spectacularly. They die a death of irrelevance. They die when the\ncultural conversation moves on and people stop thinking about it or only think\nabout how dead it is. That may eventually happen to Twitter, and it will be\ninteresting to look back at Elon&#39;s takeover with the benefit of hindsight. Was\nit the start of Twitter&#39;s death spiral? Did it save or delay Twitter&#39;s death?\nWas Twitter doomed from the beginning?<\/p>\n<p>Will Mastodon take over? I highly doubt it. People find their communities\norganically and through their existing relationships. Twitter&#39;s spiral will\nprobably have more impact for TikTok, Discord, and whatever the next big social\nnetwork will be than Mastodon. That said, Mastodon doesn&#39;t need to be the\nbiggest social network to be successful and provide the value people are looking\nfor, and I do feel it will many meet users&#39; needs there. The open source and web\ndev communities in particular seem to have found a home there.<\/p>\n<h2 id=\"looking-forward\">Looking Forward<\/h2>\n<p>Ultimately the people, communities, and relationships we&#39;ve built are all still\nhere, just a bit jumbled up now. Life goes on and I&#39;m eager to move on from all\nthis.<\/p>\n<p>I was actually planning to delete my Twitter account for a good month or so, but\nheld off as I decided to make a public archive of all my tweets now available at\n<a href=\"https:\/\/tweets.dwac.dev\/\" target=\"_blank\">tweets.dwac.dev<\/a>. Shout out to\n<a href=\"https:\/\/www.zachleat.com\/\" target=\"_blank\">Zach Leatherman<\/a> and everyone involved in\n<a href=\"https:\/\/github.com\/tweetback\/tweetback\" target=\"_blank\">Tweetback<\/a> for enabling this archive,\nas well as various tools for exporting, managing, and cleaning up raw Twitter\ndata (no alt text by default, seriously?!).<\/p>\n<p>Moving forward, you can mostly find me on Mastodon at\n<a href=\"https:\/\/techhub.social\/@develwithoutacause\" target=\"_blank\"><code>@develwithoutacause@techhub.social<\/code><\/a>.\nMy new year&#39;s resolution is to post more consistent content on my blog here as\nwell, so look forward to an end of year post about how I failed to do so.\nThere&#39;s also a new <a href=\"https:\/\/blog.dwac.dev\/social\/\">social<\/a> page here listing out everywhere you can\nfind me. I just started a\n<a href=\"https:\/\/www.youtube.com\/@develwithoutacause\" target=\"_blank\">YouTube channel<\/a> too and published\nmy first video on <a href=\"https:\/\/www.youtube.com\/watch?v=zL0TzFY6aj0\" target=\"_blank\">HydroActive<\/a>.\nI&#39;m hoping to take advantage of that channel for more cool web dev content in\nthe future.<\/p>\n<p>I hope to see you around, in whatever community we happen to cross paths.<\/p>\n"},{"title":"Streamable HTML Fragments","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/"}},"updated":"2022-09-24T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/","content":"<h1 id=\"streamable-html-fragments\">Streamable HTML Fragments<\/h1>\n<time datetime=\"2022-09-24T19:00:00.000Z\" class=\"timestamp\">September 24, 2022<\/time><p>In my recent <a href=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/\">HTML fragments blog post<\/a>, I explored how\nto dynamically fetch a fully-encapsulated, server-side rendered (SSR) web\ncomponent and use it without any custom tooling or &quot;HTML-over-the-wire&quot;\nframework.<\/p>\n<p>I suggested that the web spec could be updated to better support this use case,\nand it could improve over my prototype by supporting <em>streamed<\/em> HTML fragments.\nI did not explore streaming too much in that post as I didn&#39;t think it was\npossible to demo, even in a limited capacity.<\/p>\n<p>However, I recently found <a href=\"https:\/\/youtu.be\/LLRig4s1_yA\" target=\"_blank\">this HTTP 203 video<\/a>\nwhere <a href=\"https:\/\/twitter.com\/jaffathecake\" target=\"_blank\">Jake Archibald<\/a> discussed some &quot;magic\ntricks&quot; with the HTML parser. Near the end of the video, they mentioned\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/DOMImplementation\/createHTMLDocument\" target=\"_blank\"><code>document.implementation.createHTMLDocument()<\/code><\/a>\nwhich can stream dynamic HTML content directly into the page DOM. I&#39;d never\nheard of this API before, and it seemed like a great tool to stream HTML\nfragments, so I was eager to prototype the approach.<\/p>\n<p>Oh how naive I was.<\/p>\n<h2 id=\"idea\">Idea<\/h2>\n<p>If you haven&#39;t read the <a href=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/\">HTML fragments post<\/a>, I highly\nrecommend it, I could use the extra traffic \ud83d\ude09. But if not, the main idea was\nthat custom elements and declarative shadow DOM (DSD) can support a completely\nself-contained, SSR&#39;d UI component. Such a component could then be fetched via\nXHR as an &quot;HTML fragment&quot; which gets parsed into a DOM node and appended into\nthe document. This allows us to encapsulate all the implementation details of a\ncomponent, shift the rendering work to the server, and provide dynamic features\nwithout requiring a page refresh.<\/p>\n<p>One example of what a complete HTML fragment server response might look like\n(for a Twitter clone):<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>template<\/span> <span class=\"token attr-name\">shadowroot<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>open<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>link<\/span> <span class=\"token attr-name\">rel<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>stylesheet<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.css<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Hello world from tweet #1234.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>Edit<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>template<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Then the client could request and use this fragment by appending it to the DOM.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> parseDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ See HTML fragments post for implementation.<\/span>\n\n<span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Fetch an HTML fragment from the server.<\/span>\n    <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\/tweet?id=1234<\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Parse it into an `HTMLTemplateElement` node.<\/span>\n    <span class=\"token keyword\">const<\/span> template<span class=\"token operator\">:<\/span> HTMLTemplateElement <span class=\"token operator\">=<\/span>\n        <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Append to the document.<\/span>\n    document<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">appendChild<\/span><span class=\"token punctuation\">(<\/span>\n        template<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Combining this with streaming support, could we evolve this into something like:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> streamDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Implementation TBD...<\/span>\n\n<span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Fetch an HTML fragment from the server.<\/span>\n    <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\/tweet?id=1234<\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Stream the fragment into a DOM node. We only have the<\/span>\n    <span class=\"token comment\">\/\/ top-level DOM node right now, `&lt;my-tweet>&lt;\/my-tweet>`<\/span>\n    <span class=\"token comment\">\/\/ from the above example, but content will continue to<\/span>\n    <span class=\"token comment\">\/\/ stream in as it is received.<\/span>\n    <span class=\"token keyword\">const<\/span> fragment<span class=\"token operator\">:<\/span> Node <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">streamDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Append to the document.<\/span>\n    document<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">appendChild<\/span><span class=\"token punctuation\">(<\/span>fragment<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>How hard could it be right?<\/p>\n<h2 id=\"html-streaming-background\">HTML Streaming Background<\/h2>\n<p>You might be wondering why <code>streamDomFragment()<\/code> returns a <code>Node<\/code> and not an\n<code>AsyncGenerator&lt;Node, void, void&gt;<\/code>. After all, if the point is to stream the\ncontent, why would we return a fully parsed <code>Node<\/code>?<\/p>\n<p>This is important to the rest of the streaming discussion, so some background in\nhow HTML streaming actually works can help clear this up. HTML is a textual\nformat, meaning a start tag (<code>&lt;div&gt;<\/code>) can be far away from its associated close\ntag (<code>&lt;\/div&gt;<\/code>). However DOM is a hierarchical structure. There are no start or\nend tags, you either have an <code>HTMLDivElement<\/code> object or you don&#39;t. Close tags\ndon&#39;t actually exist! <em>You&#39;ve been lied to all your life by big browser!<\/em><\/p>\n<p>Browsers handle this by creating and appending a DOM node when an HTML start tag\nparsed. The close tag serves only as a signal to the parser that subsequent HTML\ngoes <em>after<\/em> that DOM node, rather than <em>inside<\/em> it.<\/p>\n<p>Let&#39;s assume the browser received the following HTML content in a few different\nchunks. How might it render this content at each pause?<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>1<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Hello,\n\n<span class=\"token comment\">&lt;!-- Pause --><\/span>\n\n        World!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token comment\">&lt;!-- Pause --><\/span>\n\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>2<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Howdy, World!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>At the first pause, the browser renders:<\/p>\n<pre><code>HTMLDivElement [\n    HTMLSpanElement [\n        Text &quot;Hello,&quot;\n    ]\n]\n<\/code><\/pre><p>I&#39;m deliberately writing this without using HTML syntax, because the DOM is a\nhierarchical structure (remember: close tags don&#39;t exist, wake up sheeple!).<\/p>\n<p>At the second pause, the span tag is fully parsed and the browser remembers\nwhere the first half was rendered, so it appends to the existing text node:<\/p>\n<pre><code>HTMLDivElement [\n    HTMLSpanElement [\n        Text &quot;Hello, World!&quot;\n    ]\n]\n<\/code><\/pre><p>Finally, after parsing the third chunk the browser sees the closing <code>&lt;\/div&gt;<\/code> tag\nand knows that any following nodes append <em>after<\/em> that associated\n<code>HTMLDivElement<\/code>, so we finally end up with:<\/p>\n<pre><code>HTMLDivElement [\n    HTMLSpanElement [\n        Text &quot;Hello, World!&quot;\n    ]\n]\nHTMLSpanElement [\n    Text &quot;Howdy, World!&quot;\n]\n<\/code><\/pre><p>There&#39;s a lot more nuances to HTML streaming (what happens if I remove the\n<code>HTMLDivElement<\/code> during the first pause?) But this should be good enough to\nunderstand the rest of this post, so I&#39;ll stop there. The aforementioned\n<a href=\"https:\/\/www.youtube.com\/watch?v=LLRig4s1_yA\" target=\"_blank\">HTTP 203 video<\/a> goes into more\ndetail on HTML streaming and with great visual aids. I highly recommend it if\nthis seems interesting to you.<\/p>\n<h2 id=\"first-node-problem\">First Node Problem<\/h2>\n<p>With that out of the way, I want to build a similar streaming mechanism. Users\nshould call <code>streamDomFragment()<\/code> and get back a <code>Node<\/code> which is initially empty\nwith no children. Users can then append it to the DOM wherever they like. As the\nremaining HTML content is streamed in, it should update that existing root node\nwith the streamed DOM.<\/p>\n<p>I started with a relatively simple implementation which read the HTTP response\nas a text stream and wrote each chunk to a new document from\n<code>document.implementation.createHTMLDocument()<\/code>, since it already implements this\nstreamed parsing behavior.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/**\n * Returns a Node which renders the streamed HTML content\n * from the given response.\n *\/<\/span>\n<span class=\"token keyword\">export<\/span> <span class=\"token keyword\">async<\/span> <span class=\"token keyword\">function<\/span> <span class=\"token function\">streamDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token operator\">:<\/span> Response<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span>\n        <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span>Node<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> body <span class=\"token operator\">=<\/span> res<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token operator\">!<\/span>body<span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">throw<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Error<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'...'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Convert the `ReadableStream&lt;Uint8Array>` to<\/span>\n    <span class=\"token comment\">\/\/ `AsyncGenerator&lt;string, void, void>`. Omitted for brevity.<\/span>\n    <span class=\"token keyword\">const<\/span> textStream<span class=\"token operator\">:<\/span> AsyncGenerator<span class=\"token operator\">&lt;<\/span><span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span> <span class=\"token operator\">=<\/span>\n        <span class=\"token function\">parseText<\/span><span class=\"token punctuation\">(<\/span><span class=\"token function\">iterateReader<\/span><span class=\"token punctuation\">(<\/span>body<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Parse the text to a new `Node` and return it.<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token function\">streamingParse<\/span><span class=\"token punctuation\">(<\/span>textStream<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/** Write the text into a new document and return it. *\/<\/span>\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">streamingParse<\/span><span class=\"token punctuation\">(<\/span>\n    stream<span class=\"token operator\">:<\/span> AsyncGenerator<span class=\"token operator\">&lt;<\/span><span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Node <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> doc<span class=\"token operator\">:<\/span> Document <span class=\"token operator\">=<\/span>\n        document<span class=\"token punctuation\">.<\/span>implementation<span class=\"token punctuation\">.<\/span><span class=\"token function\">createHTMLDocument<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Read all chunks in the background, don't block the<\/span>\n    <span class=\"token comment\">\/\/ current execution.<\/span>\n    <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">for<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> chunk <span class=\"token keyword\">of<\/span> stream<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n            doc<span class=\"token punctuation\">.<\/span><span class=\"token function\">write<\/span><span class=\"token punctuation\">(<\/span>chunk<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token punctuation\">}<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token keyword\">return<\/span> doc<span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p><code>Document<\/code> extends <code>Node<\/code>, so <code>streamingParse()<\/code> has a valid return value.\nHowever, attempting to append a <code>Document<\/code> to an existing document doesn&#39;t work.<\/p>\n<pre><code>index.ts:17 Uncaught (in promise) DOMException: Failed to\nexecute &#39;appendChild&#39; on &#39;Node&#39;: Nodes of type &#39;#document&#39;\nmay not be inserted inside nodes of type &#39;MAIN&#39;.\n<\/code><\/pre><p>This makes a certain level of sense, you can&#39;t put a document inside another\ndocument. So we need a <code>Node<\/code> to append to the document at the start of the\nstream, but what <code>Node<\/code> could that be? It <em>should<\/em> be a <code>&lt;my-tweet \/&gt;<\/code> element,\nbut this code is running before the HTTP response is received, so we don&#39;t\nactually know what the <code>Node<\/code> will be. It could be <code>&lt;my-other-tweet \/&gt;<\/code> or a\ndreaded <code>&lt;mean-tweet \/&gt;<\/code>.<\/p>\n<p>To solve this, I had to stream enough of the input to parse the root level node\nand then return that node to be inserted into the document while the rest of the\nresponse was received. This was especially tricky given that I needed to consume\nthe rest of the stream asynchronously, so I can&#39;t just use <code>for await<\/code> with a\n<code>break<\/code>, since that would close the stream in an un-resumable fashion. I\nultimately ended up with:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/** Write the text into a new document and return it. *\/<\/span>\n<span class=\"token keyword\">async<\/span> <span class=\"token keyword\">function<\/span> <span class=\"token function\">streamingParse<\/span><span class=\"token punctuation\">(<\/span>\n    stream<span class=\"token operator\">:<\/span> AsyncGenerator<span class=\"token operator\">&lt;<\/span><span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span>Node<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> doc <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span>implementation<span class=\"token punctuation\">.<\/span><span class=\"token function\">createHTMLDocument<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Use the async iterator API to read the stream<\/span>\n    <span class=\"token comment\">\/\/ imperatively until the top-level Node is parsed.<\/span>\n    <span class=\"token comment\">\/\/ https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Iteration_protocols#the_async_iterator_and_async_iterable_protocols<\/span>\n    <span class=\"token keyword\">let<\/span> root<span class=\"token operator\">:<\/span> Node <span class=\"token operator\">|<\/span> <span class=\"token keyword\">null<\/span> <span class=\"token operator\">=<\/span> <span class=\"token keyword\">null<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">while<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ Wait for the next chunk to arrive.<\/span>\n        <span class=\"token keyword\">const<\/span> it <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> stream<span class=\"token punctuation\">.<\/span><span class=\"token function\">next<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>it<span class=\"token punctuation\">.<\/span>done<span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">throw<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Error<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Failed to parse a root node out of the stream.'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Write the chunk to the streamable document.<\/span>\n        doc<span class=\"token punctuation\">.<\/span><span class=\"token function\">write<\/span><span class=\"token punctuation\">(<\/span>it<span class=\"token punctuation\">.<\/span>value<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Look to see if the root node has been parsed.<\/span>\n        root <span class=\"token operator\">=<\/span> doc<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span>firstChild<span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>root<span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">break<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token comment\">\/\/ Read all remaining chunks in the background, but<\/span>\n    <span class=\"token comment\">\/\/ don't block the current execution.<\/span>\n    <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">for<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> chunk <span class=\"token keyword\">of<\/span> stream<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n            doc<span class=\"token punctuation\">.<\/span><span class=\"token function\">write<\/span><span class=\"token punctuation\">(<\/span>chunk<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token punctuation\">}<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token keyword\">return<\/span> root<span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>It is definitely awkward, but works well enough for this demo.<\/p>\n<h2 id=\"streaming-declarative-shadow-dom\">Streaming Declarative Shadow DOM<\/h2>\n<p>Once I had that working I was able to actually see a streamed tweet in the DOM!\nWell, a streamed tweet without its declarative shadow DOM as the console\nindicated:<\/p>\n<pre><code>Found declarative shadowroot attribute on a template, but\ndeclarative Shadow DOM has not been enabled by includeShadowRoots.\n<\/code><\/pre><p>Apparently <code>document.implementation.createHTMLDocument()<\/code> does not support\ndeclarative shadow DOM and provides no option to enable it. I even found\n<a href=\"https:\/\/source.chromium.org\/chromium\/chromium\/src\/+\/main:third_party\/blink\/renderer\/core\/dom\/dom_implementation.cc;l=108;drc=fde2db9853cab5681586ea71d877f4cefd5eee13\" target=\"_blank\">the line in Chromium source code<\/a>\nwhich explicitly turns it off! I have never contributed to Chromium before, but\nit feels like a pretty trivial change to plumb through an option from JS. I\nthink the main hold up is about bike-shedding the exact option name\n<a href=\"https:\/\/github.com\/whatwg\/dom\/issues\/912\" target=\"_blank\">in the spec<\/a>.<\/p>\n<p>Absent proper declarative shadow DOM support, it is possible to\n<a href=\"https:\/\/web.dev\/declarative-shadow-dom\/#polyfill\" target=\"_blank\">polyfill the feature<\/a>.\nTypically this is done as a one-time transformation over the entire document,\nsince DSD is a parser-only feature by design. However, this streaming use case\nbreaks that invariant since we might stream DSD into an existing document after\nit has been fully parsed. I adjusted the polyfill to use a\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/MutationObserver\" target=\"_blank\"><code>MutationObserver<\/code><\/a>\nand scoped only to the root element of the HTML fragment being pulled into the\nDOM.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/**\n * Clone the given template and attach it to its parent's\n * shadow root.\n *\/<\/span>\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">applyDsd<\/span><span class=\"token punctuation\">(<\/span>template<span class=\"token operator\">:<\/span> HTMLTemplateElement<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token keyword\">void<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> mode <span class=\"token operator\">=<\/span> template<span class=\"token punctuation\">.<\/span><span class=\"token function\">getAttribute<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'shadowroot'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token operator\">!<\/span>mode<span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">return<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Create a shadow root for its parent and append the content.<\/span>\n    <span class=\"token keyword\">const<\/span> shadowRoot <span class=\"token operator\">=<\/span>\n        template<span class=\"token punctuation\">.<\/span>parentElement<span class=\"token operator\">!<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">attachShadow<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n            mode<span class=\"token operator\">:<\/span> mode <span class=\"token keyword\">as<\/span> ShadowRootMode<span class=\"token punctuation\">,<\/span>\n        <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">const<\/span> contents <span class=\"token operator\">=<\/span> template<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    shadowRoot<span class=\"token punctuation\">.<\/span><span class=\"token function\">appendChild<\/span><span class=\"token punctuation\">(<\/span>contents<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    template<span class=\"token punctuation\">.<\/span><span class=\"token function\">remove<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/**\n * Observes DSD templates added to the `Node` and applies\n * them to their parents.\n *\/<\/span>\n <span class=\"token keyword\">function<\/span> <span class=\"token function\">fixupDeclarativeShadowDom<\/span><span class=\"token punctuation\">(<\/span>root<span class=\"token operator\">:<\/span> Node<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token keyword\">void<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Apply any DSD nodes already parsed. This can happen<\/span>\n    <span class=\"token comment\">\/\/ if a DSD node is in the first chunk.<\/span>\n    <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>root<span class=\"token punctuation\">.<\/span>nodeType <span class=\"token operator\">===<\/span> Node<span class=\"token punctuation\">.<\/span><span class=\"token constant\">ELEMENT_NODE<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">const<\/span> templates <span class=\"token operator\">=<\/span> <span class=\"token builtin\">Array<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">from<\/span><span class=\"token punctuation\">(<\/span>\n            <span class=\"token punctuation\">(<\/span>root <span class=\"token keyword\">as<\/span> Element<span class=\"token punctuation\">)<\/span>\n                <span class=\"token punctuation\">.<\/span><span class=\"token function\">querySelectorAll<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'template[shadowroot]'<\/span><span class=\"token punctuation\">)<\/span>\n        <span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">as<\/span> HTMLTemplateElement<span class=\"token punctuation\">[<\/span><span class=\"token punctuation\">]<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token keyword\">for<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> template <span class=\"token keyword\">of<\/span> templates<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n            <span class=\"token function\">applyDsd<\/span><span class=\"token punctuation\">(<\/span>template<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token punctuation\">}<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token comment\">\/\/ Watch for any further mutations to the `root` node.<\/span>\n    <span class=\"token keyword\">const<\/span> obs <span class=\"token operator\">=<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">MutationObserver<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">(<\/span>records<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">for<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> record <span class=\"token keyword\">of<\/span> records<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n            <span class=\"token keyword\">for<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> added <span class=\"token keyword\">of<\/span> record<span class=\"token punctuation\">.<\/span>addedNodes<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n                <span class=\"token comment\">\/\/ Check if an added node is a DSD element.<\/span>\n                <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token operator\">!<\/span><span class=\"token punctuation\">(<\/span>added <span class=\"token keyword\">instanceof<\/span> <span class=\"token class-name\">HTMLElement<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">continue<\/span><span class=\"token punctuation\">;<\/span>\n                <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>added<span class=\"token punctuation\">.<\/span>tagName <span class=\"token operator\">!==<\/span> <span class=\"token string\">'TEMPLATE'<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">continue<\/span><span class=\"token punctuation\">;<\/span>\n\n                <span class=\"token function\">applyDsd<\/span><span class=\"token punctuation\">(<\/span>added <span class=\"token keyword\">as<\/span> HTMLTemplateElement<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n            <span class=\"token punctuation\">}<\/span>\n        <span class=\"token punctuation\">}<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    obs<span class=\"token punctuation\">.<\/span><span class=\"token function\">observe<\/span><span class=\"token punctuation\">(<\/span>root<span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">{<\/span> childList<span class=\"token operator\">:<\/span> <span class=\"token boolean\">true<\/span><span class=\"token punctuation\">,<\/span> subtree<span class=\"token operator\">:<\/span> <span class=\"token boolean\">true<\/span> <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> obs<span class=\"token punctuation\">.<\/span><span class=\"token function\">disconnect<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/** Write the text into a new document and return it. *\/<\/span>\n<span class=\"token keyword\">async<\/span> <span class=\"token keyword\">function<\/span> <span class=\"token function\">streamingParse<\/span><span class=\"token punctuation\">(<\/span>\n    stream<span class=\"token operator\">:<\/span> AsyncGenerator<span class=\"token operator\">&lt;<\/span><span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span>Node<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> doc <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span>implementation<span class=\"token punctuation\">.<\/span><span class=\"token function\">createHTMLDocument<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token keyword\">const<\/span> root<span class=\"token operator\">:<\/span> Node <span class=\"token operator\">=<\/span> <span class=\"token comment\">\/* ... *\/<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Watch for DSD elements streamed in and apply their contents.<\/span>\n    <span class=\"token keyword\">const<\/span> stopFixingDsd <span class=\"token operator\">=<\/span> <span class=\"token function\">fixupDeclarativeShadowDom<\/span><span class=\"token punctuation\">(<\/span>root<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">try<\/span> <span class=\"token punctuation\">{<\/span>\n            <span class=\"token keyword\">for<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> chunk <span class=\"token keyword\">of<\/span> stream<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n                doc<span class=\"token punctuation\">.<\/span><span class=\"token function\">write<\/span><span class=\"token punctuation\">(<\/span>chunk<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n            <span class=\"token punctuation\">}<\/span>\n        <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">finally<\/span> <span class=\"token punctuation\">{<\/span>\n            <span class=\"token comment\">\/\/ Remove the `MutationObserver` once all the<\/span>\n            <span class=\"token comment\">\/\/ content has been streamed.<\/span>\n            <span class=\"token function\">stopFixingDsd<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token punctuation\">}<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token keyword\">return<\/span> root<span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>With that, the tweet is actually rendering! Notice how the <code>&lt;my-tweet \/&gt;<\/code> node\nis immediately created because the server returned it instantly, while the\nrest of the content streams in afterwards.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1280\" height=\"720\" controls=\"\" style=\"aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/1-single-node-streaming.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1280\" height=\"720\" controls=\"\" style=\"aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/1-single-node-streaming.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><h2 id=\"streaming-a-list\">Streaming a List<\/h2>\n<p>Of course, streaming a single tweet probably is not actually worth the effort.\nInstead, I would much rather stream a <em>list<\/em> of tweets into the document one at\na time. So I updated the server&#39;s HTML fragment response to serve multiple\ntweets with a delay between each one.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>template<\/span> <span class=\"token attr-name\">shadowroot<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>open<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>link<\/span> <span class=\"token attr-name\">rel<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>stylesheet<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.css<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Hello world from tweet #1234.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>Edit<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>template<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n<span class=\"token comment\">&lt;!-- Delay 250ms. --><\/span>\n\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>template<\/span> <span class=\"token attr-name\">shadowroot<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>open<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>link<\/span> <span class=\"token attr-name\">rel<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>stylesheet<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.css<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Hello world from tweet #4321.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>Edit<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>template<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>However, when I tried this, I only actually saw one tweet appear.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1280\" height=\"720\" controls=\"\" style=\"aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/2-list-stream-fail.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1280\" height=\"720\" controls=\"\" style=\"aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/2-list-stream-fail.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>I eventually came to realize that <code>streamingParse()<\/code> returns a single <code>Node<\/code>,\nbut my HTTP response actually contains two top-level <code>&lt;my-tweet \/&gt;<\/code> nodes. It\ndoesn&#39;t make sense to return only the first node in the response, because more\ncould stream in and they&#39;re left in the document from\n<code>document.implementation.createHTMLDocument()<\/code>.<\/p>\n<p>To add complexity, I wanted to stream these tweets into a list, meaning I wanted\nthe final rendered DOM to be:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>...<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>...<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>ul<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Even if I successfully streamed multiple <code>&lt;my-tweet \/&gt;<\/code> nodes from the response,\nthere&#39;s no <code>&lt;li \/&gt;<\/code> tags wrapping them! I also didn&#39;t want to include the\n<code>&lt;ul \/&gt;<\/code> in the HTTP response, because I&#39;m using this stream to apply infinite\nscroll to an existing <code>&lt;ul \/&gt;<\/code> tag already containing some tweets, I don&#39;t want\nanother one for each batch of tweets.<\/p>\n<p>The simple answer is to put the <code>&lt;li \/&gt;<\/code> tags in the HTTP response like so:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>...<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>...<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>li<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Though this breaks abstraction somewhat. <code>&lt;li \/&gt;<\/code> tags aren&#39;t really standalone\nlike that and aren&#39;t intended to work outside of a <code>&lt;ul \/&gt;<\/code> or <code>&lt;ol \/&gt;<\/code> tag.<\/p>\n<p>Instead I came away with a better approach, <em>stream the top level nodes<\/em>.\nInstead of having <code>streamDomFragment()<\/code> return a single <code>Node<\/code> which gets\nautomatically updated with its children as they are streamed, let&#39;s return an\n<code>AsyncGenerator&lt;Node&gt;<\/code>. This generator emits a value for every <em>top-level<\/em> node\nin the HTTP response <em>as soon as it is parsed<\/em>, meaning the node is empty\ninitially. User code can insert this <code>Node<\/code> in the DOM where desired, and\nsubsequent streamed content will automatically append to that <code>Node<\/code> until the\nHTTP response closes it and returns a new root <code>Node<\/code>.<\/p>\n<p>Usage looks like this:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">const<\/span> list <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">getElementById<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'ul#tweet-list'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">!<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/tweets'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">for<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> myTweetEl <span class=\"token keyword\">of<\/span> <span class=\"token function\">streamDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Wrap the tweet in an `&lt;li \/>` tag.<\/span>\n    <span class=\"token keyword\">const<\/span> listItem <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'li'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    listItem<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>myTweetEl<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    list<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>listItem<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>With this, I have successfully streamed HTML fragments!<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1280\" height=\"720\" controls=\"\" style=\"aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/3-list-stream.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1280\" height=\"720\" controls=\"\" style=\"aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/3-list-stream.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>As for how to actually implement this, we can use another <code>MutationObserver<\/code> to\nwatch for additional children added to the root node of the hidden document, and\nthen detach and emit that <code>Node<\/code> as soon as we see it. The implementation here\nis especially fun, because we have to use the <code>Iterator<\/code> API directly instead of\na generator because of the <code>MutationObserver<\/code> callback. At this point, the\nimplementation code snippets tend to get a little involved, so you can check out\nthe <a href=\"https:\/\/github.com\/dgp1130\/html-fragments-demo\/tree\/blog-post-streaming\/\" target=\"_blank\">repository<\/a>\nfor the full source if you&#39;re interested.<\/p>\n<h2 id=\"chunked-streaming\">Chunked Streaming<\/h2>\n<p>The next step was to make sure my solution was reliable when receiving data in\ninconsistent ways. So rather than chunking HTTP responses by each tweet, I made\nthe server <em>randomly<\/em> chunk all the tweets, meaning multiple tweets could be in\na single chunk or it may take several chunks to finish a single tweet. As\nexpected, my implementation was very wrong. But it was wrong in <em>two<\/em>\ninteresting ways!<\/p>\n<h3 id=\"chunked-declarative-shadow-dom\">Chunked Declarative Shadow DOM<\/h3>\n<p>The first problem I immediately saw was that tweet content is visually cut off\nin weird ways:<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/4-chunked-dsd-fail.avif\" type=\"image\/avif\" width=\"762\" height=\"726\" \/>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/4-chunked-dsd-fail.webp\" type=\"image\/webp\" width=\"762\" height=\"726\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/4-chunked-dsd-fail.png\" alt=\"A screenshot of the Twitter clone implemented with HTML fragments. Five tweets have already been streamed into the document. The first four look as expected, but the last tweet is cut off. It only reads &quot;Hello world&quot; and does not include an &quot;Edit&quot; button.\" width=\"762\" height=\"726\" decoding=\"async\" loading=\"eager\" fetchpriority=\"high\" \/>\n<\/picture><\/p>\n<p>Sure enough, the response was getting chunked right in the middle of the tweet&#39;s\ndeclarative shadow DOM.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>template<\/span> <span class=\"token attr-name\">shadowroot<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>open<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>link<\/span> <span class=\"token attr-name\">rel<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>stylesheet<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.css<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Hello worl\n\n<span class=\"token comment\">&lt;!-- Delay 250ms --><\/span>\n\nd from tweet #1234.<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>Edit<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>template<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Note that DOM structure can&#39;t represent half a tag, either you have a <code>&lt;div \/&gt;<\/code>\ntag or you don&#39;t, there is no in-between. This means that when the browser\nreceives only the first chunk, it actually renders the content:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>template<\/span> <span class=\"token attr-name\">shadowroot<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>open<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>link<\/span> <span class=\"token attr-name\">rel<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>stylesheet<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.css<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Hello worl<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>template<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Normally, this is fine, since the parser is aware of this behavior and will\nupdate the DOM correctly once the rest of the content streams in. However, since\nthe <code>&lt;template \/&gt;<\/code> tag gets appended to <code>&lt;my-tweet \/&gt;<\/code>, it also triggers the\n<code>MutationObserver<\/code> and my DSD polyfill, which clones and appends that content\ndirectly under <code>&lt;my-tweet \/&gt;<\/code>. Doing so deletes the <code>&lt;template \/&gt;<\/code> tag, and any\nfuture streamed content gets dropped. So you end up with this DOM structure in\nthe end:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    #shadowRoot\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>link<\/span> <span class=\"token attr-name\">rel<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>stylesheet<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.css<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Hello worl<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>The problem here is that HTML streaming is applied as discrete DOM operations\nwith arbitrary pauses based on network activity. Once the next chunk arrives,\nthe browser will update the existing <code>&lt;template \/&gt;<\/code> tag with something like:<\/p>\n<pre><code class=\"language-typescript\">dsdTemplate<span class=\"token punctuation\">.<\/span>textContent <span class=\"token operator\">=<\/span> <span class=\"token string\">'...'<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>However, there&#39;s no way to know when or <em>if<\/em> that will ever happen. There&#39;s also\nno mechanism for knowing when an HTML element is fully parsed, so we can never\nbe sure that we have the full <code>&lt;template \/&gt;<\/code> tag and all its contents.<\/p>\n<h3 id=\"chunk-web-component-upgrades\">Chunk Web Component Upgrades<\/h3>\n<p>The second problem was that <code>this.shadowRoot<\/code> was sometimes <code>null<\/code> in\n<code>connectedCallback()<\/code>. It took quite a bit of debugging, but the exact\ncase is when the browser receives a chunk which looks like this:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>And yeah, just that. As soon as the browser sees <code>&gt;<\/code>, it creates a DOM element\nfor the node and appends it, so the DOM actually looks like:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>At this point, the element is connected to the document and invokes\n<code>connectedCallback()<\/code>. But since the <code>&lt;template shadowroot=&quot;open&quot; \/&gt;<\/code> node\nhasn&#39;t been parsed yet, the shadow root hasn&#39;t been added either! This means any\nwork to be done on the shadow root <em>must<\/em> be done lazily, even after\n<code>connectedCallback()<\/code>.<\/p>\n<p>This is a bit of pain for a developer, but you can work around it with getters\nor other programming tricks. However, the use case which really stings is event\nlisteners. It&#39;s pretty common to see a pattern like this:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">MyTweet<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token function\">connectedCallback<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token keyword\">void<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>shadowRoot<span class=\"token operator\">!<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">querySelector<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'button#edit'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">!<\/span>\n            <span class=\"token punctuation\">.<\/span><span class=\"token function\">addEventListener<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'click'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>onEdit<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token function\">disconnectedCallback<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token keyword\">void<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>shadowRoot<span class=\"token operator\">!<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">querySelector<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'button#edit'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">!<\/span>\n            <span class=\"token punctuation\">.<\/span><span class=\"token function\">removeEventListener<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'click'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>onEdit<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>However, this approach completely falls over when streamed because the shadow\nroot won&#39;t be attached until <em>after<\/em> the node is connected. The network could be\narbitrarily slow and anything could happen to <code>&lt;my-tweet \/&gt;<\/code> after it is\nattached. In fact, even <code>disconnectedCallback()<\/code> can be invoked before the\nshadow root is attached if the JavaScript code chooses to remove it before any\nmore content is received from the server.<\/p>\n<p>To make matters worse, as far as I could find, there is no hook or event which\ntriggers when the shadow root is attached, meaning there&#39;s no way to wait on it\nbefore attaching event listeners.<\/p>\n<p>This is particularly troublesome if you want to use this approach to build\n&quot;hybrid&quot; components, ones which can render on the server and reuse that DOM on\nthe client, but also can render themselves completely client-side when\nrequested. The\n<a href=\"https:\/\/web.dev\/declarative-shadow-dom\/#hydration\" target=\"_blank\">declarative shadow DOM explainer on web.dev<\/a>\neven specifically calls out a pattern which <em>directly conflicts<\/em> with streaming\nthe component&#39;s contents:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">MyTweet<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">super<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ WRONG! `this.shadowRoot` could be attached later<\/span>\n        <span class=\"token comment\">\/\/ when the parser gets to the child `&lt;template \/>`.<\/span>\n        <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token operator\">!<\/span><span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>shadowRoot<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n            <span class=\"token keyword\">const<\/span> shadow <span class=\"token operator\">=<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">attachShadow<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> mode<span class=\"token operator\">:<\/span> <span class=\"token string\">'open'<\/span> <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n            shadow<span class=\"token punctuation\">.<\/span>innerHTML <span class=\"token operator\">=<\/span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">&lt;button id=\"edit\">Edit&lt;\/button><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token punctuation\">}<\/span>\n\n        <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>shadowRoot<span class=\"token punctuation\">.<\/span><span class=\"token function\">querySelector<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'button#edit'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">!<\/span>\n            <span class=\"token punctuation\">.<\/span><span class=\"token function\">addEventListener<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'click'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>onEdit<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Ignoring the fact that this uses <code>innerHTML<\/code> and attaches an event listener in\nthe constructor, it just doesn&#39;t work in a streaming use case.\n<code>this.shadowRoot<\/code> will be <code>null<\/code> for an unspecified amount of time until the DSD\ngets parsed and attached. If you call <code>this.attachShadow()<\/code> in the constructor,\nthen once the DSD downloads it will fail to attach because a shadow root already\nexists on the element.<\/p>\n<p>You also can&#39;t know if the element will ever receive a DSD and as I mentioned\nearlier <em>there&#39;s no hook to know when the element is fully parsed!<\/em><\/p>\n<p>This problem technically exists if you eagerly load your custom element&#39;s JS and\nthen use DSD in your main HTML response. However as long as you use\n<code>&lt;script defer \/&gt;<\/code> or <code>&lt;script type=&quot;module&quot; \/&gt;<\/code> your JS will wait until all the\nHTML is parsed, and this isn&#39;t an issue. It seems like the HTML fragments use\ncase just happens to fall into this rough edge of DSD streaming.<\/p>\n<p>All of this effectively means - <strong>it is really hard to write a web component\nwhich is compatible with HTML fragment streaming<\/strong>.<\/p>\n<h3 id=\"streaming-complete-chunks\">Streaming Complete Chunks<\/h3>\n<p>My approach to these two problems is to change the streaming model for HTML just\na little bit. Traditionally, streamed HTML renders each node into DOM\nimmediately when the start tag is received by the browser and then continues to\nappend their contents as they arrive from the server until the end tag is\nreached. This always struck me as a bit non-ideal, since it can easily show\ncontent which isn&#39;t meant to be laid out or viewed without subsequent nodes.\nThis can cause of cumulative layout shift (CLS) for example if you&#39;ve streamed\nyour main content into the page, but haven&#39;t streamed the right side panel just\nyet and didn&#39;t account for that case in your CSS.<\/p>\n<p>While non-ideal, I can understand that it&#39;s tricky for developers to communicate\nto the browser when and how to stream different parts of the HTML document into\nbrowser DOM. In the context of a streamed HTML fragment however, developers&#39;\nhave a bit more context around the exact usage of this particular piece of DOM\nand the best way to stream it.<\/p>\n<p>Based around this, instead of appending empty nodes to the DOM and letting the\nbrowser lazily fill them in, let&#39;s instead <em>wait<\/em> until the node is fully parsed\nand only <em>then<\/em> append the completed node into the DOM.<\/p>\n<p>This means the node is fully rendered to the DOM <em>before<\/em> it is ever visible to\nthe user and the DSD operation can happen as a one-time transform over the DOM\nwith all the template contents and without risking splitting the template in\nhalf.<\/p>\n<p>But didn&#39;t I just say there&#39;s no way to know when a node is fully parsed? Well,\nthe node won&#39;t give you any signal, but its sibling will suddenly appear.\nConsider this minimal example:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>1<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>2<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p><code>my-tweet#1<\/code> never signals that it is done parsing, <em>but<\/em> a <code>MutationObserver<\/code>\ncan detect that <code>my-tweet#2<\/code> was appended to the DOM, and if the parser got to\nthe second tweet, it must have already full parsed the first one.<\/p>\n<p>The tricky part with this strategy in general is that the DOM is a hierarchical\nstructure, not a linear one. Tracking when a deeply nested node is fully parsed\nis quite tricky, and streaming intermediate nodes requires them to exist in two\ndifferent documents at the same time. It basically requires you to reimplement\nHTML streaming in user-land, which I definitely don&#39;t want to do here.<\/p>\n<p>However, in the context of streamed HTML fragment, we have root nodes in the\nHTTP response which are much more amenable to this approach. As soon as\n<code>my-tweet#2<\/code> is appended to the background document, detach <code>my-tweet#1<\/code> and\nappend it to the DOM! This provides an excellent time to apply the DSD polyfill,\nknowing that the element is fully parsed. It also looks great as a user, since\nthere is only one repaint when a new tweet is fully received, no rendered\nhalf-tweets!<\/p>\n<p>This approach was never the intention of this design and it&#39;s kind of a hack to\nworkaround the lack of native DSD support in the streaming DOM APIs. However, I\nactually like the end result a lot better and find it much easier to work with\nas a developer.<\/p>\n<h2 id=\"custom-element-constructors-and-field-initializers\">Custom element constructors and field initializers<\/h2>\n<p>We&#39;re not done yet though! I&#39;ve got one more interesting behavior I discovered\nalong the way. Does anything look strange with this snippet?<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">UserComponent<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> name<span class=\"token operator\">?<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">,<\/span> UserComponent<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> el <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">as<\/span> UserComponent<span class=\"token punctuation\">;<\/span>\nel<span class=\"token punctuation\">.<\/span>name <span class=\"token operator\">=<\/span> <span class=\"token string\">'devel'<\/span><span class=\"token punctuation\">;<\/span>\ndocument<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token punctuation\">.<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'devel'<\/span>\n\n<span class=\"token keyword\">const<\/span> doc <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span>implementation<span class=\"token punctuation\">.<\/span><span class=\"token function\">createHTMLDocument<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> el2 <span class=\"token operator\">=<\/span> doc<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">as<\/span> UserComponent<span class=\"token punctuation\">;<\/span>\nel2<span class=\"token punctuation\">.<\/span>name <span class=\"token operator\">=<\/span> <span class=\"token string\">'devel'<\/span><span class=\"token punctuation\">;<\/span>\ndocument<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>el2<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>el2<span class=\"token punctuation\">.<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ undefined<\/span>\n<\/code><\/pre><p>Yes, you did read that right and I was just as perplexed! The second log\nstatement\n<a href=\"https:\/\/stackblitz.com\/edit\/typescript-4atoam?file=index.ts\" target=\"_blank\"><em>does<\/em> in fact print <code>undefined<\/code><\/a>.\nWell, it does if you&#39;re using <code>target: &#39;ES2022&#39;<\/code> or greater in your\n<code>tsconfig.json<\/code>. This took me quite a while to wrap my head around and I had to\ncall in some air support from\n<a href=\"https:\/\/tweets.dwac.dev\/1571014530058321922\/\" target=\"_blank\">#WebComponents Twitter<\/a>\nto figure it out. Let me explain.<\/p>\n<h3 id=\"class-fields-proposal\">Class Fields Proposal<\/h3>\n<p>The <a href=\"https:\/\/github.com\/tc39\/proposal-class-fields\" target=\"_blank\">class fields proposal<\/a> was\nrecently accepted into the ECMAScript (JavaScript) standard \ud83c\udf89. This means it&#39;s\nnow valid JavaScript to write:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">User<\/span> <span class=\"token punctuation\">{<\/span>\n    name <span class=\"token operator\">=<\/span> <span class=\"token string\">'devel'<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>This used to be a purely TypeScript feature, but that is no longer the case. If\nyou use <code>target: &#39;ES2022&#39;<\/code> (and don&#39;t set\n<a href=\"https:\/\/www.typescriptlang.org\/tsconfig#useDefineForClassFields\" target=\"_blank\"><code>useDefineForClassFields: false<\/code><\/a>),\nthen TypeScript will actually generate this as JS output.<\/p>\n<h3 id=\"omitted-initializers\">Omitted Initializers<\/h3>\n<p>However, initializers are optional and can be omitted. That means it is also\nvalid JS to write:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">User<\/span> <span class=\"token punctuation\">{<\/span>\n    name<span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p><code>new User().name<\/code> will be left <code>undefined<\/code> as you might expect. What you might\nnot expect is that\n<a href=\"https:\/\/github.com\/tc39\/proposal-class-fields#fields-without-initializers-are-set-to-undefined\" target=\"_blank\">it is <em>assigned<\/em> to <code>undefined<\/code><\/a>.\nThat means that regardless of whatever value it had before, it will <em>now<\/em> be\n<code>undefined<\/code>. This isn&#39;t typically easy to observe in practice, since\nconstructors generally <em>construct<\/em> things from scratch. But you can see this by\nextending a class and overriding a property:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">User<\/span> <span class=\"token punctuation\">{<\/span>\n    name <span class=\"token operator\">=<\/span> <span class=\"token string\">'devel'<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Employee<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">User<\/span> <span class=\"token punctuation\">{<\/span>\n    name<span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Employee<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ `undefined`.<\/span>\n<\/code><\/pre><p>You can also see this in custom elements because a custom element constructor is\ninvoked when a DOM element is <em>upgraded<\/em> which can happen <em>after<\/em> the element is\nalready constructed. This means you have an easy opportunity to put data on the\nobject before the constructor is invoked, and when it&#39;s invoked, any class\nfields will be assigned to their initializer, including those without an\ninitializer.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">const<\/span> el <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\nel<span class=\"token punctuation\">.<\/span>name <span class=\"token operator\">=<\/span> <span class=\"token string\">'devel'<\/span><span class=\"token punctuation\">;<\/span>\ndocument<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token punctuation\">.<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'devel'<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">UserComponent<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n    name<span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">,<\/span> UserComponent<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Upgrading...<\/span>\n\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token punctuation\">.<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ undefined<\/span>\n<\/code><\/pre><p>This makes it look like defining my web component is <em>deleting<\/em> a property on an\nexisting object! If that isn&#39;t a\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Action_at_a_distance_(computer_programming)\" target=\"_blank\">\"spooky action at a distance\"<\/a>,\nI don&#39;t know what is!<\/p>\n<p>Are you starting to the see the connection here? There&#39;s still one missing\npiece. If TS in ES2022 generates JS class field initializers which cause custom\nelement upgrades to delete existing properties on an object, why isn&#39;t this a\n<em>bigger<\/em> deal? Web components supports lazy upgrades by design, wouldn&#39;t this\nhappen for all kinds of custom elements usage?<\/p>\n<h3 id=\"upgrade-timing\">Upgrade Timing<\/h3>\n<p>It turns out, no. Because usually a web component is upgraded immediately.\nRecall the initial example, but now with an added log in the constructor:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">UserComponent<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> name<span class=\"token operator\">?<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">super<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Constructed!'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">,<\/span> UserComponent<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> el <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span>\n    <span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">as<\/span> UserComponent<span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Logs 'Constructed!'<\/span>\nel<span class=\"token punctuation\">.<\/span>name <span class=\"token operator\">=<\/span> <span class=\"token string\">'devel'<\/span><span class=\"token punctuation\">;<\/span>\ndocument<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token punctuation\">.<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'test'<\/span>\n\n<span class=\"token keyword\">const<\/span> doc <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span>implementation<span class=\"token punctuation\">.<\/span><span class=\"token function\">createHTMLDocument<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> el2 <span class=\"token operator\">=<\/span> doc<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">as<\/span> UserComponent<span class=\"token punctuation\">;<\/span>\nel2<span class=\"token punctuation\">.<\/span>name <span class=\"token operator\">=<\/span> <span class=\"token string\">'devel'<\/span><span class=\"token punctuation\">;<\/span>\ndocument<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>el2<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Logs 'Constructed!'<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>el2<span class=\"token punctuation\">.<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ undefined<\/span>\n<\/code><\/pre><p>Why does the first one work and the second one fail? Notice how the first case\nis constructed at <code>document.createElement()<\/code> while the second one is constructed\nat <code>document.body.append()<\/code>. The reasoning for this is because\n<code>document.implementation.createHTMLDocument()<\/code> is considered <em>inert<\/em>, meaning\nit&#39;s inactive and does not run scripts. This is similar to\n<a href=\"https:\/\/html.spec.whatwg.org\/multipage\/scripting.html#associated-inert-template-document\" target=\"_blank\"><code>HTMLTemplateElement.prototype.contents<\/code><\/a>.\nAfter all, you wouldn&#39;t want a <code>&lt;template \/&gt;<\/code> tag to execute its contents, bind\nevent listeners, and corrupt your global page state. You expect to first <em>clone<\/em>\nthe <code>&lt;template \/&gt;<\/code> <em>and then<\/em> have it corrupt your global page state.<\/p>\n<p>Since <code>document<\/code> is <em>not<\/em> inert, a new <code>my-user<\/code> node gets upgraded immediately\non creation. But since <code>doc<\/code> <em>is<\/em> inert, it doesn&#39;t get upgraded until it is\n&quot;adopted&quot; to an active document. This happens implicitly with\n<code>document.body.append()<\/code> which invokes the constructor then.<\/p>\n<p>These subtle timing differences mean construction is delayed until after\nproperty initialization which results in any class fields being reset to\n<code>undefined<\/code>. It&#39;s this weirdly specific combination of three completely\nunrelated nuances:<\/p>\n<ol>\n<li>TypeScript now generates JS class fields.<\/li>\n<li>Class fields without initializers overwrite any existing data to <code>undefined<\/code>.<\/li>\n<li>Inert documents don&#39;t upgrade custom elements on creation.<\/li>\n<\/ol>\n<p>While debugging this was quite involved, the fix is relatively straightforward.\nAll we need to do is force the element to upgrade when we create it, prior to\nsetting any properties. We can do this by adopting the element into the main\ndocument with either\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Document\/importNode\" target=\"_blank\"><code>document.importNode()<\/code><\/a>\nor <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Document\/adoptNode\" target=\"_blank\"><code>document.adoptNode()<\/code><\/a>.<\/p>\n<p>We can fix our original snippet by doing:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">UserComponent<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> name<span class=\"token operator\">?<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">,<\/span> UserComponent<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> doc <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span>implementation<span class=\"token punctuation\">.<\/span><span class=\"token function\">createHTMLDocument<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> el <span class=\"token operator\">=<\/span> doc<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-user'<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">as<\/span> UserComponent<span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ Upgrades here.<\/span>\n<span class=\"token keyword\">const<\/span> imported <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">importNode<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token punctuation\">,<\/span> <span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\nimported<span class=\"token punctuation\">.<\/span>name <span class=\"token operator\">=<\/span> <span class=\"token string\">'devel'<\/span><span class=\"token punctuation\">;<\/span>\ndocument<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>imported<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>imported<span class=\"token punctuation\">.<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'devel'<\/span>\n<\/code><\/pre><p>I won&#39;t pretend to understand the difference between <code>importNode()<\/code> and\n<code>adoptNode()<\/code> because I honestly don&#39;t. All I understand is that <code>importNode()<\/code>\n<em>copies<\/em> its input while <code>adoptNode()<\/code> actually <em>moves<\/em> the node by detaching it\nfrom its current document and attaching it to the new document. Also it seems\nthat <code>importNode()<\/code> implicitly upgrades any custom elements while <code>adoptNode()<\/code>\ndoes not and you need to manually call\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/CustomElementRegistry\/upgrade\" target=\"_blank\"><code>customElements.upgrade()<\/code><\/a>.<\/p>\n<p>At least all we need to do to solve this is add <code>document.importNode()<\/code> to the\nstreaming HTML fragment implementation, so the fix was easy.<\/p>\n<p><strong>But wait, there&#39;s more!<\/strong><\/p>\n<h3 id=\"first-html-fragment\">First HTML Fragment<\/h3>\n<p><code>document.importNode()<\/code> only upgrades custom elements which are\n<em>already defined<\/em>. It can&#39;t upgrade elements which have not been defined yet!<\/p>\n<p>In the case of HTML fragments, a web component&#39;s definition is intended to be\nself contained in its own fragment.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>template<\/span> <span class=\"token attr-name\">shadowroot<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>open<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>link<\/span> <span class=\"token attr-name\">rel<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>stylesheet<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.css<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Here is a tweet!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>template<\/span><span class=\"token punctuation\">><\/span><\/span>\n\n    <span class=\"token comment\">&lt;!-- `my-tweet` is defined here. --><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>This presents a bit of a paradox. Consider the following constraints:<\/p>\n<ol>\n<li>We can&#39;t set a property on the <code>&lt;my-tweet \/&gt;<\/code> node until <em>after<\/em> the element\nis upgraded, or the property will be deleted on upgrade.<\/li>\n<li>The first time <code>&lt;my-tweet \/&gt;<\/code> is appended to the DOM, it won&#39;t upgrade until\n <code>customElements.define(&#39;my-tweet&#39;, MyTweet);<\/code> is executed from the\n <code>&lt;script \/&gt;<\/code> tag.<\/li>\n<li>The <code>&lt;script \/&gt;<\/code> tag does not execute until <em>after<\/em> <code>&lt;my-tweet \/&gt;<\/code> is\nappended to the DOM.<\/li>\n<\/ol>\n<p>There is simply no convenient opportunity to set properties on a streamed custom\nelement. You <em>have<\/em> to append it to the DOM, wait for the script to be executed,\nand only <em>then<\/em> set the properties you want on a element.<\/p>\n<p>My solution to this is a <code>preloadScripts()<\/code> function which finds all\n<code>&lt;script \/&gt;<\/code> tags in the fragment and appends them to the DOM to execute them\nand wait for their completion. This is definitely a hack, but\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-fragments#custom-elements\">as I mentioned in the last post<\/a>,\n<a href=\"https:\/\/github.com\/WICG\/webcomponents\/blob\/c351fc9\/proposals\/html-modules-explainer.md\" target=\"_blank\">HTML modules<\/a>\nshould be able to fix this particular issue. Basically, you use it like this:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> streamDomFragment<span class=\"token punctuation\">,<\/span> preloadScripts <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">import<\/span> <span class=\"token keyword\">type<\/span> <span class=\"token punctuation\">{<\/span> MyTweet <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/tweet.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/tweets'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">for<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> fragment <span class=\"token keyword\">of<\/span> <span class=\"token function\">streamDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ `fragment` is a new `Fragment` type, holding the<\/span>\n    <span class=\"token comment\">\/\/ contents of the HTML fragment. Important this is<\/span>\n    <span class=\"token comment\">\/\/ *not* a `Node`; it can't be used in the DOM directly.<\/span>\n\n    <span class=\"token comment\">\/\/ const tweet = fragment.cloneContent() as MyTweet;<\/span>\n    <span class=\"token comment\">\/\/ WRONG! While we can clone the HTML fragment like a<\/span>\n    <span class=\"token comment\">\/\/ `HTMLTemplateElement`, we shouldn't cast it to<\/span>\n    <span class=\"token comment\">\/\/ `MyTweet` because that script hasn't executed yet.<\/span>\n    <span class=\"token comment\">\/\/ Any setters or methods defined in that class aren't<\/span>\n    <span class=\"token comment\">\/\/ loaded and can't be used yet.<\/span>\n\n    <span class=\"token comment\">\/\/ Execute the `&lt;script \/>` tags in the fragment to make<\/span>\n    <span class=\"token comment\">\/\/ sure any custom elements are defined. `MyTweet` is<\/span>\n    <span class=\"token comment\">\/\/ upgraded here.<\/span>\n    <span class=\"token keyword\">await<\/span> fragment<span class=\"token punctuation\">.<\/span><span class=\"token function\">preloadScripts<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ RIGHT! Cast is valid *now* since `MyTweet` is defined.<\/span>\n    <span class=\"token comment\">\/\/ Setters and methods are functional now.<\/span>\n    <span class=\"token keyword\">const<\/span> tweet <span class=\"token operator\">=<\/span> fragment<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneContent<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">as<\/span> MyTweet<span class=\"token punctuation\">;<\/span>\n\n    document<span class=\"token punctuation\">.<\/span><span class=\"token function\">getElementById<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-tweet-list'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>tweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>My suggestion is that whenever you use an HTML fragment as a pre-rendered web\ncomponent, you should <em>always<\/em> call <code>preloadScripts()<\/code> before casting to that\nweb component&#39;s type.<\/p>\n<p><code>streamDomFragment()<\/code> <em>could<\/em> do that automatically, but I don&#39;t think it\nactually should because any other side effects in the script would be applied\n<em>before<\/em> its containing fragment is actually in the document. For example, you\ncould not do:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>button<\/span> <span class=\"token attr-name\">id<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>hi<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>Say hi!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>button<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><span class=\"token language-javascript\">\n        <span class=\"token comment\">\/\/ Error: `document.getElementById('hi')` is `null`<\/span>\n        <span class=\"token comment\">\/\/ because it's executed in `preloadScripts()`, prior to<\/span>\n        <span class=\"token comment\">\/\/ the `&lt;button \/>` being appended to the DOM.<\/span>\n        document<span class=\"token punctuation\">.<\/span><span class=\"token function\">getElementById<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'hi'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">addEventListener<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'click'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n            <span class=\"token function\">alert<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Howdy!'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <\/span><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>div<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>The framework designer in me wants to make a separate <code>streamWebComponents()<\/code>\nAPI which assumes \/ asserts that you&#39;re streaming custom elements and\nauto-preloads scripts to reduce the likelihood of misuse, but this is all\nexperimental so let&#39;s not overthink it just yet.<\/p>\n<p>Alternatively you can use <code>target: &#39;ES2020&#39;<\/code> or earlier. You can also set\n<code>useDefineForClassFields: false<\/code> to tell TypeScript not to generate real JS\nclass fields, but those both seem like short term solutions given that\nTypeScript is just mimicking JavaScript behavior. HTML modules would codify the\nright behavior in my opinion, and I think that&#39;s the long term fix for this\nissue. Although figuring out how to make that work with this kind of streaming\nmodel is a entirely new scale of problem.<\/p>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Whew! That&#39;s a lot of nonsense to get through, but in the end we have a very\nsmooth Twitter clone which can stream tweets with only the snippet:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> streamDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> tweetsList <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">querySelector<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'ul#tweet-list'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> streamTweetsBtn <span class=\"token operator\">=<\/span>\n    document<span class=\"token punctuation\">.<\/span><span class=\"token function\">getElementById<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'streamTweetsBtn'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\nstreamTweetsBtn<span class=\"token punctuation\">.<\/span><span class=\"token function\">addEventListener<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'click'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Fetch an HTML fragment of multiple tweets.<\/span>\n    <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/tweets'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">.<\/span><span class=\"token function\">status<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">>=<\/span> <span class=\"token number\">400<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">throw<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Error<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'...'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Stream the results.<\/span>\n    <span class=\"token keyword\">for<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> tweet <span class=\"token keyword\">of<\/span> <span class=\"token function\">streamDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ Each time we receive a tweet, wrap it in an<\/span>\n        <span class=\"token comment\">\/\/ `&lt;li \/>` tag and append it to the list.<\/span>\n        <span class=\"token keyword\">const<\/span> li <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'li'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        li<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>tweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        tweetsList<span class=\"token punctuation\">.<\/span><span class=\"token function\">append<\/span><span class=\"token punctuation\">(<\/span>li<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre>\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1280\" height=\"720\" controls=\"\" style=\"aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/3-list-stream.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1280\" height=\"720\" controls=\"\" style=\"aspect-ratio: 1280 \/ 720; max-height: 720px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/demos\/3-list-stream.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>I&#39;d say that&#39;s mission accomplished.<\/p>\n<p>There are a few details I skipped over. For example, did you know that a\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/ShadowRoot\" target=\"_blank\"><code>ShadowRoot<\/code><\/a>\ncan&#39;t be cloned? This required some hacks to clone the declarative shadow DOM in\nan HTML fragment <em>before<\/em> it gets converted to a real <code>ShadowRoot<\/code>.<\/p>\n<p>I learned quite a few interesting things here:<\/p>\n<ul>\n<li><code>document.implementation.createHTMLDocument()<\/code> allows you to manually stream\nHTML.<\/li>\n<li>You can&#39;t stream the way HTML normally streams because DSD and <code>&lt;script \/&gt;<\/code>\ntags aren&#39;t natively supported and aren&#39;t feasible to implement in user-space.<\/li>\n<li>You also probably don&#39;t <em>want<\/em> to stream in the typical manner because the web\ncomponent lifecycle becomes untenable.<\/li>\n<li>You <em>can<\/em> stream by waiting for individual top-level elements, and this\nactually works out much more conveniently for developers.<\/li>\n<li>TypeScript now generates JS class fields in ES2022+.<\/li>\n<li>JS class fields without initializers can &quot;delete&quot; data from an existing\nobject.<\/li>\n<li>Web components parsed from another document get upgraded too late and lose any\nassigned properties.<\/li>\n<li>The HTML fragments pattern loads custom element definitions <em>after<\/em> appending\nthem to the DOM, making property initialization much more difficult.<\/li>\n<li>All these points combined lead to a lot of pain and suffering...<\/li>\n<\/ul>\n<p>You can check out the\n<a href=\"https:\/\/github.com\/dgp1130\/html-fragments-demo\/tree\/blog-post-streaming\/\" target=\"_blank\">full source code on GitHub<\/a>\nand play around with it.\n<a href=\"https:\/\/techhub.social\/@develwithoutacause\/\" target=\"_blank\">Let me know what you think<\/a> or try\nit out yourself!<\/p>\n<p>I was expecting this project to only take a couple hours and 3 weeks later, I\nthink it <em>may<\/em> have fallen a little out of hand. But I know just the solution...<\/p>\n<p>\ud83d\udeeb\ud83c\udfd6\ufe0f\ud83d\udecc<\/p>\n"},{"title":"Impressions of Rust","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/rust-impressions\/"}},"updated":"2022-08-06T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/rust-impressions\/","content":"<h1 id=\"impressions-of-rust\">Impressions of Rust<\/h1>\n<time datetime=\"2022-08-06T19:00:00.000Z\" class=\"timestamp\">August 6, 2022<\/time><p>I recently had an opportunity to write some production Rust code and as a\nprogramming language nerd I was very interested in the opportunity to experience\nwhat Rust development is really like and had a few observations to share.<\/p>\n<p>A few years ago I went through <a href=\"https:\/\/doc.rust-lang.org\/book\/\" target=\"_blank\">the Rust book<\/a>\nand found a lot to like in the language, but never had an excuse to do much with\nit. Now I was working through an issue to\n<a href=\"https:\/\/github.com\/dgp1130\/rules_prerender\/issues\/46\/\" target=\"_blank\">switch <code>@rules_prerender<\/code> CSS bundling to use Parcel<\/a>\nand required some changes to\n<a href=\"https:\/\/github.com\/parcel-bundler\/parcel-css\/tree\/9916cae0499e74ebcfafd5f0367edadbecebf3ca\/\" target=\"_blank\">Parcel's Rust codebase<\/a>\nto make that happen. Specifically, I wanted to add support for a custom\nresolver, so <code>@import<\/code> statements in CSS could be resolved to arbitrary paths on\nthe file system in order to be compatible with <code>bazel-out\/<\/code> file structure. I\nalso wanted that resolver to be implementable in JavaScript, so\n<code>rules_prerender<\/code> wouldn&#39;t need to ship custom Rust code, which would introduce\nsignificant deployment complexity which it wouldn&#39;t otherwise need to deal with.<\/p>\n<p>Updating Parcel to support a custom JS resolver pulled on a number of\ninteresting challenges, including:<\/p>\n<ul>\n<li>Working with <code>async<\/code>\/<code>await<\/code><\/li>\n<li>Working with multi-threading<\/li>\n<li>JavaScript interoperability<\/li>\n<li><a href=\"https:\/\/napi.rs\/\" target=\"_blank\">Node-API<\/a><\/li>\n<\/ul>\n<p>Based on this experience, here are a few observations about the Rust language\nand ecosystem. Keep in mind that it&#39;s my first real foray into Rust (aside from\nsome toy programs) and I&#39;m coming at this from a web developer perspective, not\na systems programming perspective (I did a lot of C\/C++ college but barely\ntouched it since).<\/p>\n<h2 id=\"borrow-checking\">Borrow Checking<\/h2>\n<p>The borrow checker is easily the biggest feature and selling point of the Rust\nlanguage, and there&#39;s a lot to like there. Having a static analysis tool\ndirectly built into the compiler and the language design which points out memory\nsafety bugs and how to fix them is truly incredible, especially in an\nincreasingly security-minded industry. In my entire experience, I never\nencountered any runtime failures. I only ever saw one segmentation fault when I\ntried to use\n<a href=\"https:\/\/doc.rust-lang.org\/stable\/std\/mem\/fn.transmute.html\" target=\"_blank\"><code>std::mem::transmute()<\/code><\/a>\nas a hacky workaround for something it was definitely <em>not<\/em> supposed to\ntransmute, so that one is on me.<\/p>\n<p>And it&#39;s not just removing segfault errors, but also having the confidence to\nknow that I&#39;m using any given API correctly. It removes an entire dimension of\ndocumentation around ownership, thread safety, and the responsibilities of the\ncallee and the caller. This allows the compiler to subtly guide the developer\ntowards the correct solution to their particular problem.<\/p>\n<p>But while the borrow checker is a huge benefit in comparison to a C++ world, I\ndo see some significant regressions in comparison to a JavaScript world. As a\nweb developer in the build tooling space, I frequently hear suggestions that we\nrewrite existing tooling in native-compiled languages like Rust or Go. There are\nmany caveats to that approach, but the one I&#39;ll mention here is that moving from\na garbage collected world to a borrow checked world introduces a significant\nlearning and conceptual overhead bourne by the developer.<\/p>\n<p>There are now a whole new class of potential issues, design considerations, and\nchallenges that Rust introduces to web developers which I think is often\nunder-estimated. While writing Rust I frequently heard myself saying: &quot;but I\njust <em>don&#39;t care<\/em> about this ownership error, fixing this doesn&#39;t help me do\nwhat I actually want to do&quot;. Of course, in a Rust program you do care, you\n<em>have<\/em> to care about this stuff.<\/p>\n<p>The mental model is so different from what I&#39;m used to that I&#39;m never 100% sure\nI&#39;m actually solving a particular problem the &quot;right&quot; way. Are my lifetimes set\nup correctly? Does my ownership make sense? Am I using the right primitives for\nthis problem? In this context, I was making a PR for a repo I had no prior\nrelationship with, so I didn&#39;t have the luxury of a co-worker whom I could tap\non the shoulder and ask to sanity check this kind of stuff.<\/p>\n<p>These points aren&#39;t so much a critique of Rust, as they are the trade-offs it\nhas made as a language and the level of abstraction the developer sits at. Are\nyou writing code in which you care about the memory layout, data ownership, and\nallocation? If so, Rust is probably a great option in that space. But if not,\nit&#39;s likely the wrong tool for the job.<\/p>\n<p>I can at least appreciate the strongly opinionated nature of the Rust language\nand how clearly it communicates exactly what you&#39;re getting into with it: a\nworld of zero-cost abstractions, minimal runtime, and memory safety. <em>Rust is\nvery unapologetically itself<\/em>, and I mean that in the best possible way. However\nit&#39;s also important to recognize that these aren&#39;t exactly features, they&#39;re\n<em>trade-offs<\/em>. And what the language traded for them was complexity in the mental\nmodel. That&#39;s not necessarily a bad trade-off, and I&#39;m glad Rust went the\ndirection it did. However, this is a trade-off to keep in mind whenever faced\nwith the question &quot;Should we use Rust to solve this problem?&quot;<\/p>\n<h2 id=\"debugging\">Debugging<\/h2>\n<p>The Rust compiler itself is great at calling out errors, detailing what&#39;s wrong,\nwhy its wrong, and what your options are to fix it. Visualizing this as a graph,\nwe can model this developer journey like so, where the Rust compiler guides the\ndeveloper down of web of flawed solutions to the correct solution.<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/rust-impressions\/1-ideal-debugging.avif\" type=\"image\/avif\" width=\"781\" height=\"471\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/rust-impressions\/1-ideal-debugging.webp\" alt=\"A graph with dozens of nodes with arrows connecting them. The legend identifies these nodes as &quot;possible solutions&quot;, while the arrows are &quot;error messages&quot;, guiding the developer from one solution to another. At the end of the graph is a green node labeled &quot;actual solution&quot; with a single path of green arrows leading from the start to that final solution.\" width=\"781\" height=\"471\" decoding=\"async\" loading=\"eager\" fetchpriority=\"high\" \/>\n<\/picture><\/p>\n<p>This is awesome and often leads to the compiler helping you &quot;discover&quot; aspects\nof the problem space that might not have been obvious. Unfortunately the reality\nis that the path to success is simply not always clear, and my developer journey\nusually looked more like this:<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/rust-impressions\/2-actual-debugging.avif\" type=\"image\/avif\" width=\"801\" height=\"489\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/rust-impressions\/2-actual-debugging.webp\" alt=\"The same graph as before, but with an additional red line labeled &quot;Me&quot;. The line scribbles all over the graph as it attempts to find the green path, but consistently fails. It takes wrong turns, doubles backs, and even returns back to the starting node before eventually finding its way to the final solution.\" width=\"801\" height=\"489\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<p>Fixing one ownership issue often just shifts the problem to another place, and\nwithout a strong understanding of this mental model, it can be very difficult to\nidentify which path from any given node is actually the &quot;right&quot; one, which gets\ncloser to the real solution.<\/p>\n<p>As a concrete example of this, during my work here I initially tried to\neverything synchronous and single-threaded since the codebase was not <code>async<\/code>\nand I figured that would make the initial implementation easier. I found that\nthis actually made things <em>harder<\/em> because of a\n<a href=\"https:\/\/github.com\/parcel-bundler\/parcel-css\/issues\/174#issuecomment-1133549664\" target=\"_blank\">non-obvious chain of complexity<\/a>:<\/p>\n<ol>\n<li>Interoperability with JavaScript in this context inherently pulls on\nmulti-threading concepts.<ul>\n<li>The Parcel codebase was already multi-threaded, so everything needed to\nbe <code>Send + Sync<\/code> compatible, with no easy &quot;chill compiler, this is just\na prototype&quot; workaround.<\/li>\n<\/ul>\n<\/li>\n<li>Multi-threading in this context inherently pulls on <code>async<\/code>\/<code>await<\/code> issues.<ul>\n<li>The Rust function exposed to JS <em>could<\/em> work synchronously, but since I\nhad to use thread-safe APIs, they expected the main thread to be free\nfor the JS event loop, which is non-trivial to do without\n<code>async<\/code>\/<code>await<\/code>.<\/li>\n<\/ul>\n<\/li>\n<li>Using <code>async<\/code>\/<code>await<\/code> in this manner in Rust means we need to make the JS\ncall <code>async<\/code> as well.<\/li>\n<\/ol>\n<p>It took several hours to figure out that the problem &quot;<code>x<\/code> is not <code>Send + Sync<\/code>&quot;\neffectively <em>requires<\/em> the solution &quot;Make the JS function <code>async<\/code>&quot; and my\nattempts to solve a smaller-scale problem (single-threaded, no <code>async<\/code>\/<code>await<\/code>)\nwere actually making things <em>harder<\/em>, rather than <em>easier<\/em>.<\/p>\n<p>A lack of escape hatches can also make things trickier to debug. If I don&#39;t\nunderstand a value in TypeScript, I can usually cast to <code>any<\/code> and\n<code>console.log()<\/code> to understand what that value is and how I should be using it.\nThere&#39;s no real equivalent in Rust as far as I can tell. You can\n<code>println!(&quot;{:?}&quot;, value)<\/code> if the type implements <code>Debug<\/code> (Node-API JS types do\nnot), but there&#39;s no easy <code>as any<\/code> or a good way of debugging lifetime issues.\nA lot of this is just the different mental model Rust uses, so an <code>as any<\/code>\nwouldn&#39;t help anyways, and I&#39;m not sure what reasonable approach would allow\nignoring or tweaking invalid lifetimes to get a program that would help you\nfigure out what their correct lifetimes should be.<\/p>\n<p>On several occasions I found myself with a program which <em>I<\/em> considered to be\nvalid and memory-safe, but struggled to convince the Rust compiler that it <em>is\nindeed<\/em> a valid memory-safe program. Sometimes the compiler would point out a\nflaw in my understanding and help guide me to the correct solution, but the\ncompiler just as frequently had a flaw in its own understanding which I was\nfailing to communicate to it. Those errors are particularly frustrating because\nthe time and effort spent doesn&#39;t feel productive since it isn&#39;t about the\nproblem you actually want to solve, but rather getting the language and its\ntooling to <em>let you<\/em> solve the problem.<\/p>\n<p>Of course, debugging is hard in general, and that&#39;s true for any language. A\ncompiler can never know the exact solution to any particular error, only some\ngeneral ideas of a direction you can take that might lead to a fix. I think the\nchallenge with Rust is that the increased complexity and lower level of\nabstraction (compared to JS) makes this a bigger issue than I&#39;m used to.<\/p>\n<p>The flip side of this is that when the compiler <em>does<\/em> successfully indicate a\nflaw in your reasoning and communicates it to you effectively, Rust can feel\nincredibly productive. When it all clicks, the compiler teaches you something\nabout the problem space which you didn&#39;t realize, and you successfully follow\nthat green path on the first try, it feels <em>amazing<\/em>. Those instances are\ndefinitely the most fun I&#39;ve had programming in a long time. And isn&#39;t that what\nreally matters?<\/p>\n<h2 id=\"documentation\">Documentation<\/h2>\n<p>On a more positive note, I absolutely <em>love<\/em> <a href=\"https:\/\/docs.rs\/\" target=\"_blank\">docs.rs<\/a>, which\npulls API documentation from published crates. This is a really cool way of\nmaking documentation consistently available for all crates without having to go\nhunting for how each package does things and following types between them.\nClicking through functions and type definitions is so smooth and consistent,\njust a fantastic experience all around.<\/p>\n<p>This unfortunately doesn&#39;t solve the <em>writing<\/em> part of writing documentation,\nand some crates are certainly under-documented. However I always had that\ncontent immediately at my fingertips which really helped with the process. The\nwhole thing makes me really jealous and want a similar feature for NPM.<\/p>\n<p>I do wish there was a more standard pattern for enabling features inside crates.\nOne friction point is that different crates are less up-front about all their\nfeatures, what each of them do, and which symbols are hidden behind them. I\nwould love to see a compiler error which reads &quot;<code>foo::bar<\/code> doesn&#39;t exist, but it\nis supported by the <code>foo<\/code> crate behind the <code>bar<\/code> feature, consider enabling that\nin your <code>Cargo.toml<\/code>.&quot;<\/p>\n<h2 id=\"editing\">Editing<\/h2>\n<p>I used VSCode for most of this process and found the editing experience to be\ndecent, but lacking in comparison to TypeScript (one of the gold standards for\nthis kind of thing in VSCode at least). A few of the areas which caused me\nchallenges were:<\/p>\n<ul>\n<li>The language service would frequently highlight entire function bodies as\nthe cause of an error, which gets noisy and unwieldy.<\/li>\n<li>&quot;Go to definition&quot; usually worked from my source code, but I couldn&#39;t do the\nsame from library code, leading me to visit <a href=\"https:\/\/docs.rs\/\" target=\"_blank\">docs.rs<\/a> even\nmore than I really should have needed to.<\/li>\n<li>Inspecting types via mouseover was much less helpful than I wanted. It would\noften should the declared type rather than the resolved type. So I would\nsee <code>Future&lt;Output = Self::Output&gt;<\/code> rather than <code>Future&lt;Output = i32&gt;<\/code>,\nwhich made debugging types much harder.<\/li>\n<\/ul>\n<h2 id=\"javascript-interoperability\">JavaScript Interoperability<\/h2>\n<p>Since the main goal of this work was to expose a JavaScript API for custom\nresolvers in Parcel, much of the challenge came from JS interoperability. I was\nexpecting to have to deal with <a href=\"https:\/\/webassembly.org\/\" target=\"_blank\">WebAssembly<\/a>, but\napparently Parcel still uses Node-API for the relevant API since\n<a href=\"https:\/\/github.com\/parcel-bundler\/parcel-css\/issues\/174#issuecomment-1134855878\" target=\"_blank\">WebAssembly doesn't have direct file system access<\/a>.<\/p>\n<p>If you&#39;re not familiar with it, Node-API is the system for building native\nNodeJS add-ons and calling them from JavaScript. The biggest constraint with\nthis system is that JavaScript only ever runs on the main thread, so any\nNode-API types like\n<a href=\"https:\/\/docs.rs\/napi\/latest\/napi\/struct.JsString.html\" target=\"_blank\"><code>JsString<\/code><\/a>,\n<a href=\"https:\/\/docs.rs\/napi\/latest\/napi\/struct.JsNumber.html\" target=\"_blank\"><code>JsNumber<\/code><\/a>,\nand\n<a href=\"https:\/\/docs.rs\/napi\/latest\/napi\/struct.JsFunction.html\" target=\"_blank\"><code>JsFunction<\/code><\/a>\ncan only be referenced from the main thread (not sure how JS worker interop\nworks here). Since Parcel is multi-threaded, most of the challenge came from\nfiguring out how to use these types only from the main thread.<\/p>\n<p>Fortunately Rust is really helpful here. Its ownership model ports really well\nto multithreaded programming. The JS types don&#39;t implemented <code>Send<\/code> or <code>Sync<\/code>,\nso I would get clear type errors if I ever accidentally referenced something\nfrom the wrong thread, so I never encountered any race conditions (I did kind of\n<a href=\"https:\/\/blog.dwac.dev\/posts\/rust-impressions\/#synchronous-callbacks\">get a deadlock<\/a> at one point, more on that later).\nWhenever the program compiled, it had a very high chance of actually doing what\nI wanted, which I think is a strong indicator of how good the compiler is.<\/p>\n<p>Here are a few interesting details, though if you really want the nitty-gritty\nyou can look at the\n<a href=\"https:\/\/github.com\/parcel-bundler\/parcel-css\/pull\/196\" target=\"_blank\">pull request<\/a>.<\/p>\n<h3 id=\"threadsafefunction\"><code>ThreadsafeFunction<\/code><\/h3>\n<p>There is a\n<a href=\"https:\/\/docs.rs\/napi\/latest\/napi\/threadsafe_function\/struct.ThreadsafeFunction.html\" target=\"_blank\"><code>ThreadsafeFunction<\/code><\/a>\ntype for calling JS functions from worker threads, though it took me a while to\nreally understand what this is doing and why the API is structure the way it is.\nThe <a href=\"https:\/\/docs.rs\/napi\/latest\/napi\/threadsafe_function\/struct.ThreadsafeFunction.html#example\" target=\"_blank\">example<\/a>\nis the best documentation and also does not explain most of the reasoning for\nit.<\/p>\n<pre><code class=\"language-rust\"><span class=\"token keyword\">use<\/span> <span class=\"token namespace\">napi<span class=\"token punctuation\">::<\/span><\/span><span class=\"token class-name\">JsFunction<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">use<\/span> <span class=\"token namespace\">napi<span class=\"token punctuation\">::<\/span>threadsafe_function<span class=\"token punctuation\">::<\/span><\/span><span class=\"token punctuation\">{<\/span>\n    <span class=\"token class-name\">ErrorStrategy<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token class-name\">ThreadSafeCallContext<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token class-name\">ThreadsafeFunction<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token class-name\">ThreadsafeFunctionCallMode<\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/\/ Rust type of the arguments passed to the JS function.<\/span>\n<span class=\"token keyword\">struct<\/span> <span class=\"token type-definition class-name\">JsArgs<\/span> <span class=\"token punctuation\">{<\/span>\n    message<span class=\"token punctuation\">:<\/span> <span class=\"token class-name\">String<\/span><span class=\"token punctuation\">,<\/span>\n    sender<span class=\"token punctuation\">:<\/span> <span class=\"token class-name\">String<\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">fn<\/span> <span class=\"token function-definition function\">test_threadsafe_function<\/span><span class=\"token punctuation\">(<\/span>js_func<span class=\"token punctuation\">:<\/span> <span class=\"token class-name\">JsFunction<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">-><\/span> <span class=\"token namespace\">napi<span class=\"token punctuation\">::<\/span><\/span><span class=\"token class-name\">Result<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Create a thread-safe reference to a JS function.<\/span>\n    <span class=\"token keyword\">let<\/span> threadsafe_js_func<span class=\"token punctuation\">:<\/span> <span class=\"token class-name\">ThreadsafeFunction<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token class-name\">JsArgs<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token class-name\">ErrorStrategy<\/span><span class=\"token punctuation\">::<\/span><span class=\"token class-name\">Fatal<\/span><span class=\"token operator\">><\/span> <span class=\"token operator\">=<\/span>\n        js_func<span class=\"token punctuation\">.<\/span><span class=\"token function\">create_threadsafe_function<\/span><span class=\"token punctuation\">(<\/span>\n            <span class=\"token number\">0<\/span> <span class=\"token comment\">\/* max_queue_size (0 means unlimited). *\/<\/span><span class=\"token punctuation\">,<\/span>\n            <span class=\"token comment\">\/\/ Invoked on the main thead, converts `JsArgs`<\/span>\n            <span class=\"token comment\">\/\/ to JavaScript values.<\/span>\n            <span class=\"token closure-params\"><span class=\"token closure-punctuation punctuation\">|<\/span>ctx<span class=\"token punctuation\">:<\/span> <span class=\"token class-name\">ThreadSafeCallContext<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token class-name\">JsArgs<\/span><span class=\"token operator\">><\/span><span class=\"token closure-punctuation punctuation\">|<\/span><\/span> <span class=\"token punctuation\">{<\/span>\n                <span class=\"token comment\">\/\/ Return a `Result&lt;Vec&lt;JsUnknown>>` which<\/span>\n                <span class=\"token comment\">\/\/ are passed to the JS function.<\/span>\n                <span class=\"token class-name\">Ok<\/span><span class=\"token punctuation\">(<\/span><span class=\"token macro property\">vec!<\/span><span class=\"token punctuation\">[<\/span>\n                    ctx<span class=\"token punctuation\">.<\/span>env<span class=\"token punctuation\">.<\/span><span class=\"token function\">create_string<\/span><span class=\"token punctuation\">(<\/span><span class=\"token operator\">&amp;<\/span>ctx<span class=\"token punctuation\">.<\/span>value<span class=\"token punctuation\">.<\/span>message<span class=\"token punctuation\">)<\/span><span class=\"token operator\">?<\/span>\n                        <span class=\"token punctuation\">.<\/span><span class=\"token function\">into_unknown<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n                    ctx<span class=\"token punctuation\">.<\/span>env<span class=\"token punctuation\">.<\/span><span class=\"token function\">create_string<\/span><span class=\"token punctuation\">(<\/span><span class=\"token operator\">&amp;<\/span>ctx<span class=\"token punctuation\">.<\/span>value<span class=\"token punctuation\">.<\/span>sender<span class=\"token punctuation\">)<\/span><span class=\"token operator\">?<\/span>\n                        <span class=\"token punctuation\">.<\/span><span class=\"token function\">into_unknown<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n                <span class=\"token punctuation\">]<\/span><span class=\"token punctuation\">)<\/span>\n            <span class=\"token punctuation\">}<\/span>\n        <span class=\"token punctuation\">)<\/span><span class=\"token operator\">?<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Invoked on the current thread (may not be main).<\/span>\n    threadsafe_js_func<span class=\"token punctuation\">.<\/span><span class=\"token function\">call<\/span><span class=\"token punctuation\">(<\/span><span class=\"token class-name\">JsArgs<\/span> <span class=\"token punctuation\">{<\/span>\n        message<span class=\"token punctuation\">:<\/span> <span class=\"token class-name\">String<\/span><span class=\"token punctuation\">::<\/span><span class=\"token function\">from<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"Hello!\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n        sender<span class=\"token punctuation\">:<\/span> <span class=\"token class-name\">String<\/span><span class=\"token punctuation\">::<\/span><span class=\"token function\">from<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"Rust\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token class-name\">ThreadsafeFunctionCallMode<\/span><span class=\"token punctuation\">::<\/span><span class=\"token class-name\">Blocking<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token class-name\">Ok<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>This creates a thread-safe function with <code>JsArgs<\/code> declared as its arguments.\nThis is a Rust type which represents the arguments being passed to the JS\nfunction <em>before<\/em> they are converted to their JS equivalents. It is constructed\non the worker thread and placed in a queue when <code>.call()<\/code> is invoked. Once the\nJS event loop is ready to process the invocation, it pulls the item from this\nqueue and uses the callback in <code>.create_threadsafe_function()<\/code> to convert\n<code>JsArgs<\/code> into <code>Result&lt;Vec&lt;JsUnknown&gt;&gt;<\/code>. That callback is invoked on the main\nthread, so you have full access to the JS types. This is a direct result of the\nneed to limit JS symbols to the main thread and why this API works the way it\ndoes. I think you can actually return <code>Result&lt;Vec&lt;ToNapiValue&gt;&gt;<\/code>, but if you&#39;re\nreturning heterogenous types, this can confuse the compiler. Everything has an\n<code>.into_unknown()<\/code> to convert to the base <code>JsUnknown<\/code> type which can make the\ntype homogenous.<\/p>\n<p>If you want a Rust function to return a <code>Promise<\/code> to JS, you have to use a very\nsimilar looking API called\n<a href=\"https:\/\/napi.rs\/docs\/compat-mode\/concepts\/tokio\" target=\"_blank\"><code>execute_tokio_future()<\/code><\/a>.\nThis has a similar pattern of taking a <code>Future&lt;Output = SomeRustType&gt;<\/code> and a\ntransformation function running on the main thread which converts the result to\na Node-API JS type.<\/p>\n<p>The general pattern here is that you want to do as much work as you can\n<em>outside<\/em> the callback, so it happens off the main thread. Then use the callback\nsolely to convert the arguments from Rust types into JS types.<\/p>\n<p>One other thing that tripped me up with <code>ThreadsafeFunction<\/code> in particular is\nthat Node-API uses\n<a href=\"https:\/\/docs.rs\/napi\/latest\/napi\/threadsafe_function\/ErrorStrategy\/enum.CalleeHandled.html\" target=\"_blank\"><code>ErrorStrategy::CalleeHandled<\/code><\/a>\nby default. This means the JS function should be written to receive the call\nlike so:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">function<\/span> <span class=\"token function\">myReceiver<\/span><span class=\"token punctuation\">(<\/span>err<span class=\"token operator\">:<\/span> <span class=\"token builtin\">any<\/span><span class=\"token punctuation\">,<\/span> message<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> sender<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>err<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token function\">doSomethingWithError<\/span><span class=\"token punctuation\">(<\/span>err<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">return<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token function\">doSomethingWithSuccess<\/span><span class=\"token punctuation\">(<\/span>message<span class=\"token punctuation\">,<\/span> sender<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>This follows NodeJS callback conventions, where an optional error is passed as\nthe first argument (if the <code>JsArgs<\/code> -&gt; <code>Result&lt;Vec&lt;JsUnknown&gt;&gt;<\/code> conversion\nfails), with the actual data following. In my case, there is no use case where\nthe resolver should be called with an error, so\n<a href=\"https:\/\/docs.rs\/napi\/latest\/napi\/threadsafe_function\/ErrorStrategy\/enum.Fatal.html\" target=\"_blank\"><code>ErrorStrategy::Fatal<\/code><\/a>\nmade more sense and would just call the function directly with the\n<code>Result&lt;Vec&lt;JsUnknown&gt;&gt;<\/code>.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">function<\/span> <span class=\"token function\">myReceiver<\/span><span class=\"token punctuation\">(<\/span>message<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> sender<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ No error case to worry about!<\/span>\n    <span class=\"token function\">doSomethingWithSuccess<\/span><span class=\"token punctuation\">(<\/span>message<span class=\"token punctuation\">,<\/span> sender<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Unfortunately, <code>ThreadsafeFunction<\/code> doesn&#39;t currently seem to have any support\nfor <a href=\"https:\/\/github.com\/napi-rs\/napi-rs\/blob\/548f358fdbaeba43be4a91aaec3b411a404ffb61\/crates\/napi\/src\/threadsafe_function.rs#L400\" target=\"_blank\">capturing return values<\/a>.\nThis means the resolved file path that the resolver returns gets dropped\nentirely. My workaround for this was to modify the JS function signature to\ninstead use a callback to invoke Rust with the response.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token operator\">*<\/span> <span class=\"token keyword\">as<\/span> path <span class=\"token keyword\">from<\/span> <span class=\"token string\">'path'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">myResolver<\/span><span class=\"token punctuation\">(<\/span>\n    specifier<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span>\n    originatingFile<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token comment\">\/\/ Rust callback invoked with the result.<\/span>\n    <span class=\"token function-variable function\">callback<\/span><span class=\"token operator\">:<\/span> <span class=\"token punctuation\">(<\/span>err<span class=\"token operator\">:<\/span> <span class=\"token builtin\">any<\/span><span class=\"token punctuation\">,<\/span> result<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> resolved <span class=\"token operator\">=<\/span> path<span class=\"token punctuation\">.<\/span><span class=\"token function\">join<\/span><span class=\"token punctuation\">(<\/span>originatingFile<span class=\"token punctuation\">,<\/span> <span class=\"token string\">'..'<\/span><span class=\"token punctuation\">,<\/span> specifier<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token function\">callback<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">null<\/span><span class=\"token punctuation\">,<\/span> resolved<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>The Rust side then used a\n<a href=\"https:\/\/crates.io\/crates\/callback-future\" target=\"_blank\"><code>CallbackFuture<\/code><\/a> to wait\nfor this function to be invoked and capture the result. Since this would be an\nun-ergonomic API on the JS side, I added a small adapter which translated a\n<code>Promise<\/code> API structure into this callback design.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/\/ Wraps the `bundleAsync` export and converts the `resolve`<\/span>\n<span class=\"token comment\">\/\/ option from a Promise API to a callback API.<\/span>\n<span class=\"token keyword\">const<\/span> <span class=\"token punctuation\">{<\/span> bundleAsync<span class=\"token operator\">:<\/span> realBundleAsync <span class=\"token punctuation\">}<\/span> <span class=\"token operator\">=<\/span> module<span class=\"token punctuation\">.<\/span>exports<span class=\"token punctuation\">;<\/span>\nmodule<span class=\"token punctuation\">.<\/span>exports<span class=\"token punctuation\">.<\/span><span class=\"token function-variable function\">bundleAsync<\/span> <span class=\"token operator\">=<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> resolve<span class=\"token punctuation\">,<\/span> <span class=\"token operator\">...<\/span>opts <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token function\">realBundleAsync<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n        <span class=\"token operator\">...<\/span>opts<span class=\"token punctuation\">,<\/span>\n        resolve<span class=\"token operator\">:<\/span> <span class=\"token function\">normalizeJsCallback<\/span><span class=\"token punctuation\">(<\/span>resolve<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ The version of `resolve` exposed to JS implementations<\/span>\n<span class=\"token comment\">\/\/ which returns a `Promise`.<\/span>\n<span class=\"token keyword\">type<\/span> <span class=\"token class-name\">PromiseBasedResolve<\/span> <span class=\"token operator\">=<\/span> <span class=\"token punctuation\">(<\/span>\n    specifier<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span>\n    originatingFile<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token builtin\">string<\/span><span class=\"token operator\">><\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ The version of `resolve` which invokes the Rust callback.<\/span>\n<span class=\"token keyword\">type<\/span> <span class=\"token class-name\">CallbackBasedResolve<\/span> <span class=\"token operator\">=<\/span> <span class=\"token punctuation\">(<\/span>\n    specifier<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span>\n    originatingFile<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token function-variable function\">rustCallback<\/span><span class=\"token operator\">:<\/span> <span class=\"token punctuation\">(<\/span>err<span class=\"token operator\">:<\/span> <span class=\"token builtin\">any<\/span><span class=\"token punctuation\">,<\/span> result<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ Converts the Promise-based of `resolve` to the<\/span>\n<span class=\"token comment\">\/\/ callback-based version.<\/span>\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">normalizeJsCallback<\/span><span class=\"token punctuation\">(<\/span>userResolve<span class=\"token operator\">:<\/span> PromiseBasedResolve<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> CallbackBasedResolve <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token punctuation\">(<\/span>\n        specifier<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span>\n        originatingFile<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span>\n        <span class=\"token function-variable function\">rustCallback<\/span><span class=\"token operator\">:<\/span> <span class=\"token punctuation\">(<\/span>err<span class=\"token operator\">:<\/span> <span class=\"token builtin\">any<\/span><span class=\"token punctuation\">,<\/span> result<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token keyword\">void<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token builtin\">Promise<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">resolve<\/span><span class=\"token punctuation\">(<\/span><span class=\"token function\">userResolve<\/span><span class=\"token punctuation\">(<\/span>specifier<span class=\"token punctuation\">,<\/span> originatingFile<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">then<\/span><span class=\"token punctuation\">(<\/span>\n            <span class=\"token punctuation\">(<\/span>result<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token function\">rustCallback<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">null<\/span><span class=\"token punctuation\">,<\/span> result<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n            <span class=\"token punctuation\">(<\/span>err<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token function\">rustCallback<\/span><span class=\"token punctuation\">(<\/span>err<span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">null<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n        <span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ Example usage with the `Promise`-based API.<\/span>\nmodule<span class=\"token punctuation\">.<\/span>exports<span class=\"token punctuation\">.<\/span><span class=\"token function\">bundleAsync<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n    <span class=\"token function\">resolve<\/span><span class=\"token punctuation\">(<\/span>specifier<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> originatingFile<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">const<\/span> resolved <span class=\"token operator\">=<\/span>\n            path<span class=\"token punctuation\">.<\/span><span class=\"token function\">join<\/span><span class=\"token punctuation\">(<\/span>originatingFile<span class=\"token punctuation\">,<\/span> <span class=\"token string\">'..'<\/span><span class=\"token punctuation\">,<\/span> specifier<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">return<\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">resolve<\/span><span class=\"token punctuation\">(<\/span>resolved<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span>\n<\/code><\/pre><p>This gives JS implementations of <code>resolve()<\/code> a fully <code>Promise<\/code> based API, hiding\nthe ugly callback under the hood.<\/p>\n<h3 id=\"synchronous-callbacks\">Synchronous Callbacks<\/h3>\n<p>Parcel&#39;s <code>bundle()<\/code> function which I wanted to add a custom resolver to was\nactually synchronous, meaning a resolver which returns a <code>Promise<\/code> can&#39;t really\nwork. However, file resolution <em>might not<\/em> be asynchronous, such as the\n<code>path.join()<\/code> implementation above. So in theory, a synchronous <code>bundle()<\/code>\n<em>should<\/em> be possible as long as the custom resolver is synchronous, right?<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> bundle <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'@parcel\/css'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token function\">bundle<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Synchronous implementation, should work.<\/span>\n    <span class=\"token function\">resolve<\/span><span class=\"token punctuation\">(<\/span>specifier<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> originatingFile<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">return<\/span> path<span class=\"token punctuation\">.<\/span><span class=\"token function\">join<\/span><span class=\"token punctuation\">(<\/span>originatingFile<span class=\"token punctuation\">,<\/span> <span class=\"token string\">'..'<\/span><span class=\"token punctuation\">,<\/span> specifier<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">,<\/span>\n\n    <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>However this isn&#39;t possible with <code>ThreadsafeFunction<\/code>. As mentioned earlier,\n<code>ThreadsafeFunction<\/code> actually queues an invocation and waits for the main thread\nto become available, effectively scheduling an event on the\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/EventLoop\" target=\"_blank\">JavaScript event loop<\/a>.\nIf the main thread is always blocked, then the invocation will never happen.\nSince the main thread is executing the Rust implementation of <code>bundle()<\/code>, it\nnever has an opportunity to invoke the JS event loop and <code>resolve()<\/code> will never\nbe invoked. I had effectively blocked the main thread waiting for an event to\ntrigger, but an event can never trigger because the main thread is blocked.\nDeadlocked!<\/p>\n<p>The function call is still queued, so I found calling the JS function but not\nblocking on it and then adding an asynchronous timeout to the end of the\nfunction allowed <code>resolve()<\/code> to be invoked (albeit after <code>bundle()<\/code> had already\nreturned).<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> bundle <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'@parcel\/css'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ Rust call to JS `resolve()` gets scheduled here, but can't happen because the<\/span>\n<span class=\"token comment\">\/\/ main thread is still in this function.<\/span>\n<span class=\"token function\">bundle<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n    <span class=\"token function\">resolve<\/span><span class=\"token punctuation\">(<\/span>specifier<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> originatingFile<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">Resolving <\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>specifier<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token string\"> from <\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>originatingFile<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token string\">.<\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">return<\/span> path<span class=\"token punctuation\">.<\/span><span class=\"token function\">join<\/span><span class=\"token punctuation\">(<\/span>originatingFile<span class=\"token punctuation\">,<\/span> <span class=\"token string\">'..'<\/span><span class=\"token punctuation\">,<\/span> specifier<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">,<\/span>\n\n    <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ Yields to the event loop, so *now* `resolve()` gets invoked and prints.<\/span>\n<span class=\"token keyword\">await<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\"><span class=\"token builtin\">Promise<\/span><\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">(<\/span>resolve<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token function\">setTimeout<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token function\">resolve<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token number\">1_000<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>The shared main thread makes a synchronous callback with <code>ThreadsafeFunction<\/code>\nquite tricky. In Parcel&#39;s case, the main thread doesn&#39;t need to do anything\nspecial and mostly waits for worker threads \/ acts as its own worker thread. I\nbelieve it is still possible to manually free the main thread with your own\n&quot;event loop&quot; and process cross-thread JS function invocations while waiting for\nworker threads. I don&#39;t think <code>ThreadsafeFunction<\/code> actually has any API to\nsupport this, so you&#39;d basically have to re-implement your own version of\n<code>ThreadsafeFunction<\/code> to do it.<\/p>\n<p>To summarize, <code>ThreadsafeFunction<\/code> doesn&#39;t support synchronous callbacks to\nJavaScript from worker threads. The easiest solution is to make the callback\nasynchronous so the main thread returns a <code>Promise<\/code> with\n<a href=\"https:\/\/napi.rs\/docs\/compat-mode\/concepts\/tokio\" target=\"_blank\"><code>execute_tokio_future()<\/code><\/a>.<\/p>\n<h2 id=\"functional-design\">Functional Design<\/h2>\n<p>Moving away from Node-API and back to traditional Rust: I had a lot of fun with\nRust&#39;s functional design patterns. Iterators work really smoothly, <code>Option<\/code> and\n<code>Result<\/code> are fantastic, pattern matching is really expressive and intuitive, and\nenums work perfectly. I&#39;ve done some of this before in other contexts like\nHaskell, but this was my first opportunity to use APIs which are actually\n<em>designed<\/em> to use <code>Option<\/code> and <code>Result<\/code>, with first class language support for\nmonadic operations like <code>?<\/code>.<\/p>\n<p>Many of these concepts are pretty easy to add into any language, but the great\npart about Rust is that\n<a href=\"https:\/\/tweets.dwac.dev\/1554266879950065665\/\" target=\"_blank\">it has powerful, standardized primitives<\/a>\nwhich the whole ecosystem can leverage. No unexpected runtime errors and no\nunchecked nulls. This should really be the standard for all future languages and\nI would love to see a stronger effort to migrate towards these patterns in\nexisting languages.<\/p>\n<p>The one unfortunate part is that it sometimes felt like every API was returning\n<code>Result<\/code> and it littered most of the code with <code>?<\/code> operators after every call.\nIt&#39;s not that big a deal since <code>?<\/code> is such a lightweight addition, but I wonder\nhow different this really is from traditional error handling if they just get\npropagated 99% of the time anyways.<\/p>\n<h3 id=\"unions\">Unions<\/h3>\n<p>I was also a little sad that there&#39;s no equivalent to TypeScripts union operator\n(<code>|<\/code>) in Rust. This means that have a function return one of multiple things\nrequires a named enum type and can&#39;t be anonymously constructed from a union of\nexisting types.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">function<\/span> <span class=\"token function\">numberOrString<\/span><span class=\"token punctuation\">(<\/span>value<span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span> <span class=\"token operator\">|<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token keyword\">void<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">Value: <\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>value<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token function\">numberOrString<\/span><span class=\"token punctuation\">(<\/span><span class=\"token number\">1<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Value: 1<\/span>\n<span class=\"token function\">numberOrString<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'test'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Value: test<\/span>\n<\/code><\/pre><pre><code class=\"language-rust\"><span class=\"token comment\">\/\/ Must declare the enum and give it an explicit name name.<\/span>\n<span class=\"token keyword\">enum<\/span> <span class=\"token type-definition class-name\">NumberOrString<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token class-name\">IsNumber<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">i32<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token class-name\">IsString<\/span><span class=\"token punctuation\">(<\/span><span class=\"token class-name\">String<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">fn<\/span> <span class=\"token function-definition function\">number_or_string<\/span><span class=\"token punctuation\">(<\/span>value<span class=\"token punctuation\">:<\/span> <span class=\"token class-name\">NumberOrString<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">match<\/span> value <span class=\"token punctuation\">{<\/span>\n        <span class=\"token class-name\">NumberOrString<\/span><span class=\"token punctuation\">::<\/span><span class=\"token class-name\">IsNumber<\/span><span class=\"token punctuation\">(<\/span>num<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span>\n            <span class=\"token macro property\">println!<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"Value: {}\"<\/span><span class=\"token punctuation\">,<\/span> num<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n        <span class=\"token class-name\">NumberOrString<\/span><span class=\"token punctuation\">::<\/span><span class=\"token class-name\">IsString<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">str<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span>\n            <span class=\"token macro property\">println!<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"Value: {}\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">str<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">fn<\/span> <span class=\"token function-definition function\">main<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token function\">number_or_string<\/span><span class=\"token punctuation\">(<\/span><span class=\"token class-name\">NumberOrString<\/span><span class=\"token punctuation\">::<\/span><span class=\"token class-name\">IsNumber<\/span><span class=\"token punctuation\">(<\/span><span class=\"token number\">1<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Value: 1<\/span>\n    <span class=\"token function\">number_or_string<\/span><span class=\"token punctuation\">(<\/span><span class=\"token class-name\">NumberOrString<\/span><span class=\"token punctuation\">::<\/span><span class=\"token class-name\">IsString<\/span><span class=\"token punctuation\">(<\/span>\n        <span class=\"token class-name\">String<\/span><span class=\"token punctuation\">::<\/span><span class=\"token function\">from<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"test\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Value: test<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>I thought it would bother me more than it did, but it actually didn&#39;t come up\ntoo often, so it&#39;s a relatively minor complaint. You could use an implementation\nof <a href=\"https:\/\/docs.rs\/either\/latest\/either\/\" target=\"_blank\"><code>Either<\/code><\/a>, though there\ndoesn&#39;t seem to be a standard version and it doesn&#39;t scale too well. I do know\nthat <code>number | string<\/code> in TypeScript is not discriminated (no data telling me\nwhich type is in the variable, I&#39;d have to <code>typeof<\/code> it). By contrast,\n<code>NumberOrString<\/code> is discriminated which allows <code>match<\/code> to work as well as does.\nThat said, I would still love to see some kind of union operator in Rust to make\nthis a little lighter-weight for simple cases.<\/p>\n<h3 id=\"mixing-option-and-\">Mixing <code>Option<\/code> and <code>?<\/code><\/h3>\n<p>One particularly annoying challenge I came across was mapping <code>Option<\/code> types\nwith operations that might fail and how they interact with the <code>?<\/code> operator:<\/p>\n<pre><code class=\"language-rust\"><span class=\"token keyword\">fn<\/span> <span class=\"token function-definition function\">main<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">-><\/span> <span class=\"token class-name\">Result<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Works: `?` is great!<\/span>\n    <span class=\"token macro property\">println!<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"{}\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token function\">maybe_concat<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"First\"<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">\" Second\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">?<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ error[E0277]: the `?` operator can only be used in a<\/span>\n    <span class=\"token comment\">\/\/ closure that returns `Result` or `Option`<\/span>\n    <span class=\"token keyword\">let<\/span> result <span class=\"token operator\">=<\/span> <span class=\"token class-name\">Some<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"Hello\"<\/span><span class=\"token punctuation\">)<\/span>\n        <span class=\"token punctuation\">.<\/span><span class=\"token function\">map<\/span><span class=\"token punctuation\">(<\/span><span class=\"token closure-params\"><span class=\"token closure-punctuation punctuation\">|<\/span>value<span class=\"token closure-punctuation punctuation\">|<\/span><\/span> <span class=\"token function\">maybe_concat<\/span><span class=\"token punctuation\">(<\/span><span class=\"token operator\">&amp;<\/span>value<span class=\"token punctuation\">,<\/span> <span class=\"token string\">\" World\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">?<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token macro property\">println!<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"{:?}\"<\/span><span class=\"token punctuation\">,<\/span> result<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token class-name\">Ok<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">fn<\/span> <span class=\"token function-definition function\">maybe_concat<\/span><span class=\"token punctuation\">(<\/span>first<span class=\"token punctuation\">:<\/span> <span class=\"token operator\">&amp;<\/span><span class=\"token keyword\">str<\/span><span class=\"token punctuation\">,<\/span> second<span class=\"token punctuation\">:<\/span> <span class=\"token operator\">&amp;<\/span><span class=\"token keyword\">str<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">-><\/span> <span class=\"token class-name\">Result<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token class-name\">String<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token class-name\">Ok<\/span><span class=\"token punctuation\">(<\/span><span class=\"token class-name\">String<\/span><span class=\"token punctuation\">::<\/span><span class=\"token function\">from<\/span><span class=\"token punctuation\">(<\/span>first<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">+<\/span> second<span class=\"token punctuation\">)<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Since the <code>?<\/code> is used in a closure within <code>Option.map()<\/code>, is isn&#39;t able to make\nan early return from <code>main()<\/code> on failure. I couldn&#39;t find a good workaround to\nthis which used <code>.map()<\/code>, so the best I could come up with was to avoid the\nclosure altogether:<\/p>\n<pre><code class=\"language-rust\"><span class=\"token keyword\">fn<\/span> <span class=\"token function-definition function\">main<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">-><\/span> <span class=\"token class-name\">Result<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Inline the `.map()` call with a `match`.<\/span>\n    <span class=\"token comment\">\/\/ Avoids the closure, so `?` still works.<\/span>\n    <span class=\"token keyword\">let<\/span> result <span class=\"token operator\">=<\/span> <span class=\"token keyword\">match<\/span> <span class=\"token class-name\">Some<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"hello\"<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token class-name\">Some<\/span><span class=\"token punctuation\">(<\/span>value<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token class-name\">Some<\/span><span class=\"token punctuation\">(<\/span><span class=\"token function\">maybe_concat<\/span><span class=\"token punctuation\">(<\/span><span class=\"token operator\">&amp;<\/span>value<span class=\"token punctuation\">,<\/span> <span class=\"token string\">\" world\"<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">?<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n        <span class=\"token class-name\">None<\/span> <span class=\"token operator\">=><\/span> <span class=\"token class-name\">None<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token macro property\">println!<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">\"{:?}\"<\/span><span class=\"token punctuation\">,<\/span> result<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token class-name\">Ok<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>This works but just <strong>screams<\/strong> at me to use a <code>.map()<\/code> call. That <code>None =&gt; None<\/code>\nand <code>Some(value) =&gt; Some(fn(value))<\/code> is <em>exactly<\/em> what a <code>.map()<\/code> function is\nfor. I&#39;m not sure what the right solution to this would be beyond the Rust\ncompiler magically jumping out of <code>main()<\/code>, which is <em>maybe<\/em> possible, but\ndefinitely sounds like a bad idea.<\/p>\n<h2 id=\"deployment\">Deployment<\/h2>\n<p>Most of the effort here was trying to get Parcel to support custom resolvers\nimplemented in JavaScript. However I was very easily able to set up a custom\nresolver implemented in Rust. I could have stopped there and just written my own\nusage in Rust rather than JavaScript. I did consider this option but ultimately\ndecided against it because my use case was itself a JS library for others to\nconsume (called\n<a href=\"https:\/\/github.com\/dgp1130\/rules_prerender\/\" target=\"_blank\"><code>rules_prerender<\/code><\/a>, you\nshould check it out if you&#39;re into Bazel or static site generators). I could\nhave written a resolver there in Rust, but then I would run into the problem of\ndeployment, how do users depend on the Rust part of the library?<\/p>\n<p>This would have required cross-compiling my Rust resolver and Parcel into a\nbunch of different architectures, shipping them on NPM, installing the right\none, and then invoking it. This was a lot of complexity I didn&#39;t want to address\nfor a 5-line resolver, but was trivial for a JS resolver. So instead of solving\nthat problem, I decided to go through all this multi-threaded, async Node-API\nstuff contributed to a library I don&#39;t own, and write a way-too-long blog post\nabout it.<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/rust-impressions\/3-efficiency.avif\" type=\"image\/avif\" width=\"600\" height=\"400\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/rust-impressions\/3-efficiency.webp\" alt=\"The &quot;stonks&quot; meme featuring a man in a suit with a blank mannequin head looking confidently at a line graph moving up and to the right with a bunch of meaningless numbers in the background. The subtitle reads: &quot;Efficiency&quot;.\" width=\"600\" height=\"400\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<h2 id=\"adapters\">Adapters<\/h2>\n<p>An area I struggled a lot with were discovering and choosing between the many\ndifferent versions of the same operation which had slightly different semantics\nor names. For example, what kind of <code>Fn<\/code> or <code>.iter()<\/code> operation should I do? I\neventually came to understand that these have direct parallels to Rust&#39;s\nownership model:<\/p>\n<table>\n<thead>\n<tr>\n<th><\/th>\n<th>Own<\/th>\n<th>Borrow<\/th>\n<th>Mutate<\/th>\n<\/tr>\n<\/thead>\n<tbody><tr>\n<td><strong>Language<\/strong><\/td>\n<td><code>foo<\/code><\/td>\n<td><code>&amp;foo<\/code><\/td>\n<td><code>&amp;mut foo<\/code><\/td>\n<\/tr>\n<tr>\n<td><strong>Functions<\/strong><\/td>\n<td><code>FnOnce<\/code><\/td>\n<td><code>Fn<\/code><\/td>\n<td><code>FnMut<\/code><\/td>\n<\/tr>\n<tr>\n<td><strong>Iterators<\/strong><\/td>\n<td><code>.into_iter()<\/code><\/td>\n<td><code>.iter()<\/code><\/td>\n<td><code>.iter_mut()<\/code><\/td>\n<\/tr>\n<\/tbody><\/table>\n<p>Once I understood that correlation, I had a much easier time understanding which\nof these I should be using for any particular problem. Some useful references\nfor both of these are:<\/p>\n<ul>\n<li><a href=\"https:\/\/huonw.github.io\/blog\/2015\/05\/finding-closure-in-rust\/\" target=\"_blank\">Finding Closure in Rust<\/a><\/li>\n<li><a href=\"https:\/\/hermanradtke.com\/2015\/06\/22\/effectively-using-iterators-in-rust.html\" target=\"_blank\">Effectively Using Iterators in Rust<\/a><\/li>\n<\/ul>\n<p>This also helped teach me a few common conventions:<\/p>\n<ul>\n<li><code>.into_*()<\/code> means &quot;convert and take ownership&quot;.<\/li>\n<li><code>.ok_*()<\/code> means &quot;convert into a <code>Result<\/code> type&quot;.<ul>\n<li>Except for <code>Result<\/code> which confusingly converts into an <code>Option<\/code>.<\/li>\n<\/ul>\n<\/li>\n<li><code>unwrap_*()<\/code> means &quot;extract from the object&quot;.<\/li>\n<li><code>unwrap()<\/code> means &quot;extract from the object or panic because I don&#39;t want to\ndeal with error handling right now&quot;.<\/li>\n<li><code>.expect()<\/code> means &quot;assert that I got a valid result&quot;.<\/li>\n<li><code>.try_*()<\/code> means &quot;does things with <code>Result<\/code> types&quot;.<\/li>\n<\/ul>\n<p>These conventions took some time for me to get used to and I haven&#39;t seen them\nwritten down explicitly in this kind of format together, so hopefully this is\nhelpful to someone out there (also may not be 100% accurate).<\/p>\n<p>One adapter in particular that tripped me up was <code>.clone()<\/code>, specifically\n<code>&amp;str.clone()<\/code> and <code>&amp;PathBuf.clone()<\/code>. Both of these are fairly useless IMHO\nbecause they will take a borrowed reference to an object, clone it, and then\nreturn another borrowed reference. Eventually I discovered <code>.to_owned()<\/code> which\nclones the string and returns an owned version of the new object, which is\nalmost always what you would want in that situation.<\/p>\n<p><code>map()<\/code> functions also had some inconsistencies between types which I found\nquite confusing. For example:<\/p>\n<ul>\n<li><a href=\"https:\/\/doc.rust-lang.org\/std\/iter\/trait.Iterator.html\" target=\"_blank\"><code>Iterator<\/code><\/a> uses\n<a href=\"https:\/\/doc.rust-lang.org\/std\/iter\/trait.Iterator.html#method.map\" target=\"_blank\"><code>.map()<\/code><\/a> and\n<a href=\"https:\/\/doc.rust-lang.org\/std\/iter\/trait.Iterator.html#method.flat_map\" target=\"_blank\"><code>.flat_map()<\/code><\/a>.<\/li>\n<li><a href=\"https:\/\/doc.rust-lang.org\/std\/option\/enum.Option.html\" target=\"_blank\"><code>Option<\/code><\/a> uses\n<a href=\"https:\/\/doc.rust-lang.org\/std\/option\/enum.Option.html#method.map\" target=\"_blank\"><code>.map()<\/code><\/a>,\n<a href=\"https:\/\/doc.rust-lang.org\/std\/option\/enum.Option.html#method.and_then\" target=\"_blank\"><code>.and_then()<\/code><\/a>,\nand <a href=\"https:\/\/doc.rust-lang.org\/std\/option\/enum.Option.html#method.or_else\" target=\"_blank\"><code>.or_else()<\/code><\/a>.<\/li>\n<li><a href=\"https:\/\/doc.rust-lang.org\/std\/result\/enum.Result.html\" target=\"_blank\"><code>Result<\/code><\/a> uses\n<a href=\"https:\/\/doc.rust-lang.org\/std\/result\/enum.Result.html#method.map\" target=\"_blank\"><code>.map()<\/code><\/a>,\n<a href=\"https:\/\/doc.rust-lang.org\/std\/result\/enum.Result.html#method.and_then\" target=\"_blank\"><code>.and_then()<\/code><\/a>, and\n<a href=\"https:\/\/doc.rust-lang.org\/std\/result\/enum.Result.html#method.or_else\" target=\"_blank\"><code>.or_else()<\/code><\/a>.<\/li>\n<li><a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/trait.FutureExt.html\" target=\"_blank\"><code>Future<\/code><\/a>\nuses <a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/trait.FutureExt.html#method.map\" target=\"_blank\"><code>.map()<\/code><\/a>\nand <a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/trait.FutureExt.html#method.then\" target=\"_blank\"><code>.then()<\/code><\/a>.<\/li>\n<\/ul>\n<p><code>Option<\/code> and <code>Result<\/code> seem to be mostly aligned, but <code>Iterator<\/code> and <code>Future<\/code>\nboth disagree on the name of their flat map operation. The lack of function\noverloading also makes distinctions like\n<a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/trait.FutureExt.html#method.map\" target=\"_blank\"><code>Future.map()<\/code><\/a>\nvs <a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/trait.FutureExt.html#method.then\" target=\"_blank\"><code>Future.then()<\/code><\/a>\nmuch more annoying to use than they really should be.<\/p>\n<p>These adapters are also a bit tricky for documentation. Since many of them are\nimplemented as extension functions, some type documentation is fairly minimal\nand unhelpful for typical usage.\n<a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/trait.Future.html\" target=\"_blank\"><code>Future<\/code><\/a>\nis a good example of this which has a great overview of the primitive and how\npolling works, but no details about how to actually use a Future from a\npractical perspective. All the functions you really care about are under\n<a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/trait.FutureExt.html\" target=\"_blank\"><code>FutureExt<\/code><\/a>\nand much harder to find.<\/p>\n<p>This is compounded by adapter types that are never actually referenced and only\never returned and consumed by adapter functions. For example,\n<a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/trait.FutureExt.html#method.map\" target=\"_blank\"><code>Future.map()<\/code><\/a>\nmakes a lot of sense to me as a function invocation, but\n<a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/struct.Map.html\" target=\"_blank\"><code>futures::future::Map<\/code><\/a>\nas a <em>type<\/em> makes no logical sense to me. It doesn&#39;t fit a functional mental\nmodel and makes it much harder to work with. I&#39;m sure there&#39;s a good reason as\nto why these kinds of types need to exist (probably because a <code>dyn Future<\/code> isn&#39;t\n<code>Sized<\/code>?) but they clutter the API surface and documentation with noise that\nreally doesn&#39;t benefit the user. This is particularly annoying when Googling\n&quot;Rust Future map&quot; and finding\n<a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/struct.Map.html\" target=\"_blank\"><code>futures::future::Map<\/code><\/a>\ninstead of the\n<a href=\"https:\/\/docs.rs\/futures\/latest\/futures\/future\/trait.FutureExt.html#method.map\" target=\"_blank\"><code>Future.map()<\/code><\/a>\nfunction that you actually wanted.<\/p>\n<h2 id=\"async--await\"><code>async<\/code> \/ <code>await<\/code><\/h2>\n<p>I&#39;ll admit I was a bit scared to jump into <code>async<\/code> \/ <code>await<\/code> stuff when the need\narose, as I was under the impression the feature was still relatively new and\nthere was no built in runtime. Fortunately I found the experience pretty\nstraightforward and reasonably well supported. In particular, <code>await<\/code> can mostly\nbe thought of as syntactic sugar for <code>Futures<\/code>, which closely aligns to how\n<code>await<\/code> works with <code>Promises<\/code> in JavaScript and was an easy mental model to pick\nup for me.<\/p>\n<p>That said, there are some rough edges, however they are mostly smoothed over by\ncommunity crates.\n<a href=\"https:\/\/docs.rs\/async-recursion\/latest\/async_recursion\/\" target=\"_blank\">Async recursion<\/a>,\n<a href=\"https:\/\/docs.rs\/async-trait\/latest\/async_trait\/\" target=\"_blank\">async traits<\/a>, and\n<a href=\"https:\/\/docs.rs\/tokio\/latest\/tokio\/attr.test.html\" target=\"_blank\">async tests<\/a> are three areas\nin particular which stood out to me, but attribute macros mostly make things\n&quot;just work&quot; without a whole lot of issues.<\/p>\n<p>Macros in general seem like a really powerful feature, but I&#39;m not totally\nconvinced they&#39;re a good idea yet. Implementations are practically unreadable to\nme, generated code is hard to understand or debug, and compile errors become\nincredibly noisy. One error I captured looked like this:<\/p>\n<pre><code>   Compiling playground v0.0.1 (\/playground)\nerror[E0277]: `std::sync::MutexGuard&lt;&#39;_, &amp;mut Data&gt;` cannot be sent between threads safely\n  --&gt; src\/main.rs:11:1\n   |\n11 | #[async_recursion::async_recursion]\n   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `std::sync::MutexGuard&lt;&#39;_, &amp;mut Data&gt;` cannot be sent between threads safely\n   |\n   = help: within `futures::stream::futures_ordered::OrderWrapper&lt;impl futures::Future&lt;Output = Data&gt;&gt;`, the trait `std::marker::Send` is not implemented for `std::sync::MutexGuard&lt;&#39;_, &amp;mut Data&gt;`\n   = note: required because it appears within the type `for&lt;&#39;r, &#39;s, &#39;t0, &#39;t1, &#39;t2, &#39;t3, &#39;t4, &#39;t5, &#39;t6, &#39;t7, &#39;t8, &#39;t9, &#39;t10, &#39;t11, &#39;t12&gt; {ResumeTy, std::sync::Mutex&lt;&amp;&#39;r mut Data&gt;, &amp;&#39;s std::sync::Mutex&lt;&amp;&#39;t0 mut Data&gt;, Result&lt;std::sync::MutexGuard&lt;&#39;t1, &amp;&#39;t2 mut Data&gt;, PoisonError&lt;std::sync::MutexGuard&lt;&#39;t3, &amp;&#39;t4 mut Data&gt;&gt;&gt;, &amp;&#39;t5 mut std::sync::MutexGuard&lt;&#39;t6, &amp;&#39;t7 mut Data&gt;, std::sync::MutexGuard&lt;&#39;t8, &amp;&#39;t9 mut Data&gt;, &amp;&#39;t10 mut &amp;&#39;t11 mut Data, &amp;&#39;t12 mut Nested, u64, Duration, Sleep, ()}`\n   = note: required because it appears within the type `[static generator@src\/main.rs:20:91: 35:6]`\n   = note: required because it appears within the type `from_generator::GenFuture&lt;[static generator@src\/main.rs:20:91: 35:6]&gt;`\n   = note: required because it appears within the type `impl futures::Future&lt;Output = Data&gt;`\n   = note: required because it appears within the type `futures::stream::futures_ordered::OrderWrapper&lt;impl futures::Future&lt;Output = Data&gt;&gt;`\n   = note: required because of the requirements on the impl of `std::marker::Send` for `FuturesUnordered&lt;futures::stream::futures_ordered::OrderWrapper&lt;impl futures::Future&lt;Output = Data&gt;&gt;&gt;`\n   = note: required because it appears within the type `FuturesOrdered&lt;impl futures::Future&lt;Output = Data&gt;&gt;`\n   = note: required because it appears within the type `Collect&lt;FuturesOrdered&lt;impl futures::Future&lt;Output = Data&gt;&gt;, Vec&lt;Data&gt;&gt;`\n   = note: required because it appears within the type `futures::future::join_all::JoinAllKind&lt;impl futures::Future&lt;Output = Data&gt;&gt;`\n   = note: required because it appears within the type `JoinAll&lt;impl futures::Future&lt;Output = Data&gt;&gt;`\n   = note: required because it appears within the type `for&lt;&#39;r, &#39;s, &#39;t0, &#39;t1, &#39;t2, &#39;t3, &#39;t4, &#39;t5&gt; {ResumeTy, Vec&lt;Data&gt;, &amp;&#39;r mut [Data], std::slice::IterMut&lt;&#39;s, Data&gt;, [closure@src\/main.rs:20:78: 35:6], std::iter::Map&lt;std::slice::IterMut&lt;&#39;t2, Data&gt;, [closure@src\/main.rs:20:78: 35:6]&gt;, JoinAll&lt;impl futures::Future&lt;Output = Data&gt;&gt;, ()}`\n   = note: required because it appears within the type `[static generator@src\/main.rs:12:21: 39:2]`\n   = note: required because it appears within the type `from_generator::GenFuture&lt;[static generator@src\/main.rs:12:21: 39:2]&gt;`\n   = note: required because it appears within the type `impl futures::Future&lt;Output = ()&gt;`\n   = note: required for the cast to the object type `dyn futures::Future&lt;Output = ()&gt; + std::marker::Send`\n   = note: this error originates in the attribute macro `async_recursion::async_recursion` (in Nightly builds, run with -Z macro-backtrace for more info)\n\nFor more information about this error, try `rustc --explain E0277`.\nerror: could not compile `playground` due to previous error\n<\/code><\/pre><p>This was trying to tell me &quot;<code>MutexGuard<\/code> can&#39;t be passed across an <code>async<\/code>\nboundary&quot; but exactly which mutex and how the mistake is made is completely lost\nin the macro.<\/p>\n<p>While I&#39;m by no means an expert in Rust, I think I have reasonable handle on\nmost of its concepts to be able to work with them fairly effectively. One\nconcept I definitely do <em>not<\/em> understand is\n<a href=\"https:\/\/rust-lang.github.io\/async-book\/04_pinning\/01_chapter.html\" target=\"_blank\">pinning<\/a>. It\ndidn&#39;t come up too much in this particular project, but I&#39;ve encountered plenty\nof errors in the past where I have to <code>Pin<\/code> and <code>Box<\/code> all my <code>Futures<\/code> and\nwasn&#39;t able to find any explanations which really made sense to me. Hopefully\nthat&#39;s something I can get a better handle on eventually.<\/p>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>So that&#39;s a bunch of random thoughts about my experience with Rust. Overall, I\ndefinitely had a lot of fun with it and I think it&#39;s a really well designed\nlanguage. This experience has convinced me that\n<strong>I will never write C++ again<\/strong>, however\n<strong>I&#39;m not ready to abandon TypeScript just yet<\/strong>. The trade-offs Rust makes are\nonly really applicable in very particular scenarios, so I don&#39;t feel a strong\nneed to rewrite all our existing web tooling from scratch. It can certainly have\nsome value in specific circumstances, but I still believe you should profile and\noptimize your JavaScript to make sure the language and runtime is <em>actually<\/em> the\nlimiting factor and Rust gives significant performance benefits to justify the\nincrease in complexity. If so, then Rust is a fantastic option to manage that\ncomplexity, just make sure it is <em>essential<\/em> complexity and not <em>accidental<\/em>\ncomplexity.<\/p>\n"},{"title":"A Simpler HTML-over-the-Wire","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/html-fragments\/"}},"updated":"2022-03-19T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/html-fragments\/","content":"<h1 id=\"a-simpler-html-over-the-wire\">A Simpler HTML-over-the-Wire<\/h1>\n<time datetime=\"2022-03-19T19:00:00.000Z\" class=\"timestamp\">March 19, 2022<\/time><p>Recently, I was listening to some debate about client-side rendering (CSR) vs\nserver-side rendering (SSR) and struggling with how to choose which approach is\nbest for a particular project. This decision has very far reaching implications\nwith complex trade offs. CSR often leads to unnecessary tooling complexity with\nsignificant performance implications. However, SSR can limit certain dynamic\nexperiences on the client. Splitting the difference sounds nice, but often ends\nup as the worst of both worlds, having to either duplicate logic between the\nclient and server or support both platforms within the same codebase.<\/p>\n<p>This question is particularly challenging for use cases which straddle the line.\nTake <a href=\"https:\/\/twitter.com\/\" target=\"_blank\">Twitter<\/a> as an example. It just shows a bunch of\nstatic tweets and seems like a great candidate for SSR. That is, until the\nproduct manager comes to you and asks for infinite scrolling, or the ability to\nedit a tweet. Neither of these are particularly complicated, but they both\nrequire rendering a tweet after the initial page load , which is a problem for\nan SSR-committed application. You either need to commit to a full page reload,\nwhich the PM will never agree to, or you have to CSR the tweet component. Even\nif all the stakeholders agree today that Twitter should be totally static and\ngive a green light to an SSR architecture, we can never know what tomorrow&#39;s\nrequirements will bring.<\/p>\n<p>What I wanted was not so much a silver bullet architecture or framework that\naddresses every use case, but rather something which does not require me to\ncommit to either SSR, CSR, or a hybrid of the two. Is there a way we could keep\nthings low-commitment and easily changeable? I came out with this thought:<\/p>\n<!-- We use `<div role=\"blockquote\" \/>` instead of a regular\n    `<blockquote \/>` to avoid applying typical markdown styles for them. -->\n    <div role=\"blockquote\" class=\"tweet\">\n        <div class=\"author\">\n            <a href=\"https:\/\/twitter.com\/develwoutacause\/\" target=\"_blank\">\n                <picture>\n                        <source srcset=\"https:\/\/blog.dwac.dev\/res\/img\/profile.avif\" type=\"image\/avif\" \/>\n                    <img srcset=\"https:\/\/blog.dwac.dev\/res\/img\/profile.webp\" width=\"200\" height=\"200\" loading=\"lazy\" decoding=\"async\" \/>\n                <\/picture>\n            <\/a>\n        <div class=\"name\">\n                <a href=\"https:\/\/twitter.com\/develwoutacause\/\" class=\"author-name\" target=\"_blank\">Doug Parker<\/a>\n                <a href=\"https:\/\/twitter.com\/develwoutacause\/\" class=\"username\" target=\"_blank\">@develwoutacause<\/a>\n            <\/div>\n            <div class=\"source\">\n                <a href=\"https:\/\/tweets.dwac.dev\/1452082837075607553\/\" target=\"_blank\">\n                    <svg id=\"twitter-logo\" viewBox=\"0 0 24 24\" width=\"24px\" height=\"24px\">\n                        <title>Twitter logo<\/title>\n                        <g><path d=\"M23.643 4.937c-.835.37-1.732.62-2.675.733.962-.576 1.7-1.49 2.048-2.578-.9.534-1.897.922-2.958 1.13-.85-.904-2.06-1.47-3.4-1.47-2.572 0-4.658 2.086-4.658 4.66 0 .364.042.718.12 1.06-3.873-.195-7.304-2.05-9.602-4.868-.4.69-.63 1.49-.63 2.342 0 1.616.823 3.043 2.072 3.878-.764-.025-1.482-.234-2.11-.583v.06c0 2.257 1.605 4.14 3.737 4.568-.392.106-.803.162-1.227.162-.3 0-.593-.028-.877-.082.593 1.85 2.313 3.198 4.352 3.234-1.595 1.25-3.604 1.995-5.786 1.995-.376 0-.747-.022-1.112-.065 2.062 1.323 4.51 2.093 7.14 2.093 8.57 0 13.255-7.098 13.255-13.254 0-.2-.005-.402-.014-.602.91-.658 1.7-1.477 2.323-2.41z\"><\/path><\/g>\n                    <\/svg>\n                <\/a>\n            <\/div>\n        <\/div>\n        <div class=\"content\">I really wish it were possible to serve an SSR'd <a href=\"https:\/\/twitter.com\/hashtag\/HTML\" class=\"hashtag\" target=\"_blank\">#HTML<\/a> fragment (with <a href=\"https:\/\/twitter.com\/hashtag\/CSS\" class=\"hashtag\" target=\"_blank\">#CSS<\/a> and <a href=\"https:\/\/twitter.com\/hashtag\/JS\" class=\"hashtag\" target=\"_blank\">#JS<\/a>), and be able to directly insert it into the <a href=\"https:\/\/twitter.com\/hashtag\/DOM\" class=\"hashtag\" target=\"_blank\">#DOM<\/a> securely.<br \/><br \/>How many web sites could drop a client side framework if SSR'd web components could work like this?<\/div>\n        <time datetime=\"2021-10-24T01:21:00.000Z\">\n            <a href=\"https:\/\/tweets.dwac.dev\/1452082837075607553\/\" target=\"_blank\">1:21 AM - Oct 24, 2021<\/a>\n        <\/time>\n    <\/div><p>I was imagining a web server transferring small chunks of SSR&#39;d HTML fragments\nto the client as required, where the browser swaps out the content as necessary\ninto the existing page. This would provide fairly dynamic features emblematic of\nCSR&#39;d pages while keeping rendering responsibilities on the server and avoiding\na hard refresh for each change. This could support reactive functional\nrequirements, while keeping most of the components only supporting one\nenvironment (the server).<\/p>\n<p><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Web_Components\" target=\"_blank\">Web components<\/a>\nand <a href=\"https:\/\/web.dev\/declarative-shadow-dom\/\" target=\"_blank\">Declarative Shadow DOM<\/a> have\nfinally made encapsulated, component-ized, framework-less HTML a reality, so I\nwant to build a server endpoint which returns:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>template<\/span> <span class=\"token attr-name\">shadowroot<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>open<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>link<\/span> <span class=\"token attr-name\">rel<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>stylesheet<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.css<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Here is a tweet!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>template<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>And be able to append this to the current document to view the content, along\nwith its associated CSS styles and JS functionality.<\/p>\n<p>I quickly remembered that this already exists, typically referred to as\n&quot;HTML-over-the-wire&quot;, and pushed by\n<a href=\"https:\/\/dev.to\/rajasegar\/html-over-the-wire-is-the-future-of-web-development-542c\" target=\"_blank\">a few frameworks<\/a>.\nAs I did more research however, I found that these didn&#39;t really encapsulate\nwhat I was looking for. These frameworks seem to require a lot of custom tooling\nwith heavy requirements on the server itself, often leading to tight coupling\nbetween the client and server. They all felt very high-commitment. I just want\nto fetch an encapsulated DOM element, not buy an engagement ring for my server\nframework!<\/p>\n<p>Thinking on it some more, servers can return an HTML fragment pretty easily,\nit&#39;s the client that&#39;s lacking the functionality I want. What I really need is a\nway to parse that HTML into a DOM node. I then learned that this actually\nalready exists in the form of\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/DOMParser\" target=\"_blank\"><code>DOMParser<\/code><\/a>!<\/p>\n<p>I started experimenting to see how close I could get to the developer experience\nI wanted using purely native APIs and, after shooting myself in the foot a\ncouple times, found the result to be surprisingly simple. I eventually\nsimplified my example to this:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> parseDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Implementation TBD...<\/span>\n\n<span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Fetch an HTML fragment from the server.<\/span>\n    <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\/tweet?id=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>id<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Parse it into an `HTMLTemplateElement` node.<\/span>\n    <span class=\"token keyword\">const<\/span> template<span class=\"token operator\">:<\/span> HTMLTemplateElement <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Append to the document.<\/span>\n    document<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">appendChild<\/span><span class=\"token punctuation\">(<\/span>template<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Using this component is fairly straightforward:<\/p>\n<ol>\n<li>Client requests a tweet.<\/li>\n<li>Server responds with an HTML fragment.<\/li>\n<li>Client parses the HTML fragment into a synthetic <code>&lt;template \/&gt;<\/code> element with\nthe contents of the network response.<\/li>\n<li>Client clones the template and appends it to the document at the appropriate\nlocation.<\/li>\n<li>Fragment is displayed to the user and automatically loads any CSS or JS\nincluded.<\/li>\n<\/ol>\n<p>Most importantly, this is effectively zero commitment! No server framework, no\nclient framework, no magical tooling. Just a single function.<\/p>\n<h2 id=\"demo\">Demo<\/h2>\n<p>I used this pattern to put together\n<a href=\"https:\/\/github.com\/dgp1130\/html-fragments-demo\/tree\/blog-post\/\" target=\"_blank\">a very simple Twitter clone<\/a>.\nIt displays a bunch of tweets, lets you load more on demand, and even edit\nexisting tweets. Each tweet is loaded as a separate API call returning the HTML\nfragment required to render it.<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/1-base.avif\" type=\"image\/avif\" width=\"1141\" height=\"559\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/1-base.png\" alt=\"Screenshot of the demo application with Chrome DevTools visible. The application shows two lines of text as simple stand-ins for two tweets. Both lines are colored red, indicating that they have been styled. Chrome DevTools has the network tab open and shows all the requests made by the page. The list includes general resources for the page, followed by two requests to `\/tweet` with two different IDs given as query parameters. The first of these requests is currently selected and its HTTP response is displayed. The response contains a snippet of HTML with a custom element at the root using the tag name &quot;my-tweet&quot; and containing Declarative Shadow DOM, a linked stylesheet, and a `script` tag.\" width=\"1141\" height=\"559\" decoding=\"async\" loading=\"eager\" fetchpriority=\"high\" \/>\n<\/picture><\/p>\n<p>Note how DevTools shows that the tweet is transferred as an HTML fragment, using\na custom element and Declarative Shadow DOM with some JS and CSS included for\ngood measure. The timeline even shows that JS and CSS are lazily loaded the\nfirst time the <code>&lt;my-tweet \/&gt;<\/code> element is added, but also are <em>not<\/em> re-loaded\nwhen a second tweet is rendered using the same resources.<\/p>\n<p>Want to implement infinite scroll? How about:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> parseDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Implementation TBD...<\/span>\n<span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> whenUserNearBottomOfDocument <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/left-as-an-exercise-to-the-reader.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> tweetList <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">getElementById<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'tweets'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token function\">whenUserNearBottomOfDocument<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Fetch a new tweet using our superior ranking algorithm.<\/span>\n    <span class=\"token keyword\">const<\/span> id <span class=\"token operator\">=<\/span> Math<span class=\"token punctuation\">.<\/span><span class=\"token function\">floor<\/span><span class=\"token punctuation\">(<\/span>Math<span class=\"token punctuation\">.<\/span><span class=\"token function\">random<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">*<\/span> <span class=\"token number\">1000<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\/tweet?id=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>id<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Parse the tweet node from the response.<\/span>\n    <span class=\"token keyword\">const<\/span> tweetTemplate <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Add to the end of the list.<\/span>\n    tweetList<span class=\"token punctuation\">.<\/span><span class=\"token function\">appendChild<\/span><span class=\"token punctuation\">(<\/span>tweetTemplate<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Here is a demo which uses this strategy to load a new tweet each time a button\nis pressed.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 928; max-height: 928px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"928\" controls=\"\" style=\"aspect-ratio: 1920 \/ 928; max-height: 928px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/2-infinite-scroll.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"928\" controls=\"\" style=\"aspect-ratio: 1920 \/ 928; max-height: 928px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/2-infinite-scroll.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>This implements infinite scroll without having to render a tweet on the client,\ncommit to an HTML-over-the-wire framework, or use any particular server\ninfrastructure.<\/p>\n<p>You may have noticed that <code>parseDomFragment()<\/code> actually returns an\n<code>HTMLTemplateElement<\/code>, this is to allow a single fragment to be reused\nthroughout the document. We can use this to edit tweets by requesting an SSR&#39;d\n<code>&lt;my-editable-tweet \/&gt;<\/code> component exactly once, and then cloning it any time the\nuser wants to edit a tweet. We just swap out the existing tweet with an editable\nversion (@Twitter, you can have this one for free).<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/\/ Fetches the editable tweet template on startup via an IIFE.<\/span>\n<span class=\"token keyword\">const<\/span> editableTweetTemplatePromise <span class=\"token operator\">=<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span>HTMLTemplateElement<span class=\"token operator\">><\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/editable-tweet'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/** Clones an editable tweet and returns it as a `DocumentFragment`. *\/<\/span>\n<span class=\"token keyword\">async<\/span> <span class=\"token keyword\">function<\/span> <span class=\"token function\">getEditableTweet<\/span><span class=\"token punctuation\">(<\/span>tweetId<span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">,<\/span> content<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span>\n        <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span>DocumentFragment<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Clone a new editable tweet fragment.<\/span>\n    <span class=\"token keyword\">const<\/span> template <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> editableTweetTemplatePromise<span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">const<\/span> instance <span class=\"token operator\">=<\/span>\n        template<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* true *\/<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token keyword\">as<\/span> DocumentFragment<span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Set initial data.<\/span>\n    <span class=\"token keyword\">const<\/span> editableTweet <span class=\"token operator\">=<\/span> instance<span class=\"token punctuation\">.<\/span>firstElementChild <span class=\"token keyword\">as<\/span> MyEditableTweet<span class=\"token punctuation\">;<\/span>\n    editableTweet<span class=\"token punctuation\">.<\/span>tweetId <span class=\"token operator\">=<\/span> tweetId<span class=\"token punctuation\">;<\/span>\n    editableTweet<span class=\"token punctuation\">.<\/span>content <span class=\"token operator\">=<\/span> content<span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">return<\/span> instance<span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">MyTweet<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">public<\/span> tweetId<span class=\"token operator\">!<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">public<\/span> content<span class=\"token operator\">!<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">async<\/span> <span class=\"token function\">onEdit<\/span><span class=\"token punctuation\">(<\/span>newContent<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ Replace this DOM element with the editable version.<\/span>\n        <span class=\"token keyword\">const<\/span> editableTweet <span class=\"token operator\">=<\/span>\n            <span class=\"token keyword\">await<\/span> <span class=\"token function\">getEditableTweet<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>tweetId<span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">replaceWith<\/span><span class=\"token punctuation\">(<\/span>editableTweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-tweet'<\/span><span class=\"token punctuation\">,<\/span> MyTweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>The editable tweet can be its own custom element with its own behavior. Once we\nhave displayed the editable version of the tweet and the user saves their edit,\nit can <code>POST<\/code> that change to the server which will update the database and\nre-render the tweet. All the client has to do is swap the modified result back\ninto the document.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> parseDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Implementation TBD...<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">MyEditableTweet<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">public<\/span> tweetId<span class=\"token operator\">!<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">async<\/span> <span class=\"token function\">onEditSaved<\/span><span class=\"token punctuation\">(<\/span>newContent<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ Post the edit to the server, which also returns<\/span>\n        <span class=\"token comment\">\/\/ the same tweet rendered with the new content.<\/span>\n        <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span>\n            <span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\/tweet\/edit?id=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span><span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>tweetId<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token string\">&amp;content=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>\n                <span class=\"token function\">encodeURIComponent<\/span><span class=\"token punctuation\">(<\/span>newContent<span class=\"token punctuation\">)<\/span><span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">,<\/span>\n            <span class=\"token punctuation\">{<\/span> method<span class=\"token operator\">:<\/span> <span class=\"token string\">'POST'<\/span> <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">,<\/span>\n        <span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">const<\/span> editedTweetTemplate <span class=\"token operator\">=<\/span>\n            <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Replace this DOM element with the new, edited tweet.<\/span>\n        <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">replaceWith<\/span><span class=\"token punctuation\">(<\/span>\n            editedTweetTemplate<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-editable-tweet'<\/span><span class=\"token punctuation\">,<\/span> MyEditableTweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>This is able to edit the tweet on the server and get back a freshly rendered\ncopy to swap into the page over the old version.<\/p>\n\n\n<dwac-lazy class=\"video\" style=\"display: block; aspect-ratio: 1920 \/ 928; max-height: 928px;\">\n    <template>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"928\" controls=\"\" style=\"aspect-ratio: 1920 \/ 928; max-height: 928px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/3-edit.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/template>\n    <noscript>        <video autoplay=\"\" muted=\"\" loop=\"\" playsinline=\"\" width=\"1920\" height=\"928\" controls=\"\" style=\"aspect-ratio: 1920 \/ 928; max-height: 928px;\">\n                    <source src=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/3-edit.mp4\" type=\"video\/mp4\" \/>\n\n            \n        <\/video>\n<\/noscript>\n<\/dwac-lazy><p>This edit functionality\n<a href=\"https:\/\/github.com\/dgp1130\/html-fragments-demo\/blob\/blog-post\/server.ts#L62\" target=\"_blank\">reuses the existing tweet render logic<\/a>\non the server, no dual CSR\/SSR support needed! One might reasonably think that\nclient-side rendering would be more appropriate here, and that can be valid\noption. However keep in mind that an edit is not truly committed until it\nreaches the server, so making a full network request here is actually fairly\nreasonable.<\/p>\n<p>Ultimately this approach suffers a lot from the complexity of custom elements;\n<a href=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/#custom-elements\">more on that later<\/a>. You could just as easily CSR the\neditable tweet if you would rather. The beauty of this strategy is that it does\nnot lock you in to any particular framework or methodology, each component can\nrender wherever makes makes the most sense for it. You can CSR\n<code>&lt;my-editable-tweet \/&gt;<\/code> but always SSR <code>&lt;my-tweet \/&gt;<\/code> if that makes sense for\nyour design. I opted to SSR <code>&lt;my-editable-tweet \/&gt;<\/code> here simply because I\nthought that was the more interesting approach, but a CSR solution could work\njust as well!<\/p>\n<p>The above code snippets are a bit simplified, so I recommend taking a look at\nthe <a href=\"https:\/\/github.com\/dgp1130\/html-fragments-demo\/\" target=\"_blank\">full example<\/a> to see all\nthe nitty-gritty details and actual implementation of\n<a href=\"https:\/\/github.com\/dgp1130\/html-fragments-demo\/blob\/blog-post\/client\/dom.ts\" target=\"_blank\"><code>parseDomFragment()<\/code><\/a>.<\/p>\n<h2 id=\"standardization\">Standardization<\/h2>\n<p>Of course there are existing HTML-over-the-wire frameworks which make this\narchitecture more usable and handle all these edge cases for you. What really\nsurprised me though was how much of this worked out of the box with native APIs.\nSo I am wondering: What more it would take from browsers and the web\nspecification to make this kind of design easy and intuitive?<\/p>\n<p>When first thinking about this, I considered a new\n<code>Response.prototype.fragment()<\/code> function which would parse an HTTP response as\nan HTML fragment and return an <code>HTMLTemplateElement<\/code>. This could be protected\nwith\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/CSP\" target=\"_blank\">Content-Security Policy<\/a>\nand provide an easy means for using SSR&#39;d HTML fragments in an existing\ndocument. I was really excited about this and it was the original motivation for\nwriting this post.<\/p>\n<p>Like all new ideas, someone&#39;s thought of them before. As I kept iterating, I\nfound myself reminded of\n<a href=\"https:\/\/www.html5rocks.com\/en\/tutorials\/webcomponents\/imports\/\" target=\"_blank\">HTML imports<\/a>,\nan attempt at standardizing a means of &quot;importing&quot; component-ized HTML into an\nexisting document. The proposal was pushed by the Chrome web components team\nsome years ago (any\n<a href=\"https:\/\/polymer-library.polymer-project.org\/1.0\/docs\/devguide\/feature-overview\" target=\"_blank\">Polymer v1<\/a>\ndevs out there?), but has since been abandoned for a variety of reasons and was\nnever officially adopted into the web specification.<\/p>\n<p>While researching the proposal more, I discovered\n<a href=\"https:\/\/github.com\/WICG\/webcomponents\/blob\/gh-pages\/proposals\/html-modules-explainer.md\" target=\"_blank\">HTML modules<\/a>,\na successor to HTML imports which attempts to resolve some of the flaws of the\noriginal proposal, primarily by integrating the system with ES modules. This\nwould allow developers to &quot;import&quot; an HTML fragment using a regular ESM <code>import<\/code>\nstatement or a dynamic <code>import()<\/code> expression. For example, we could write the\ninfinite scroll example like so:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> whenUserNearBottomOfDocument <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/left-as-an-exercise-to-the-reader.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> tweetList <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">getElementById<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'tweets'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token function\">whenUserNearBottomOfDocument<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">async<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ `import()` a new tweet rather than `fetch()`-ing it.<\/span>\n    <span class=\"token keyword\">const<\/span> id <span class=\"token operator\">=<\/span> Math<span class=\"token punctuation\">.<\/span><span class=\"token function\">floor<\/span><span class=\"token punctuation\">(<\/span>Math<span class=\"token punctuation\">.<\/span><span class=\"token function\">random<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">*<\/span> <span class=\"token number\">1000<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">const<\/span> tweetFragment<span class=\"token operator\">:<\/span> DocumentFragment <span class=\"token operator\">=<\/span>\n        <span class=\"token keyword\">await<\/span> <span class=\"token keyword\">import<\/span><span class=\"token punctuation\">(<\/span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\/tweet.html?id=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>id<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">)<\/span>\n            <span class=\"token punctuation\">.<\/span><span class=\"token function\">then<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">(<\/span>module<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> module<span class=\"token punctuation\">.<\/span>default<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Clone the tweet element in the imported fragment.<\/span>\n    <span class=\"token keyword\">const<\/span> tweetEl <span class=\"token operator\">=<\/span>\n        tweetFragment<span class=\"token punctuation\">.<\/span>firstElementChild<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Add tweet to the end of the displayed list.<\/span>\n    tweetList<span class=\"token punctuation\">.<\/span><span class=\"token function\">appendChild<\/span><span class=\"token punctuation\">(<\/span>tweetEl<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>This approach would provide native platform capability for importing an SSR&#39;d\ntweet component and appending it to an existing document. I really like this\ndirection and think it could be a powerful addition to the web standard. I do\nwant to call out one interesting difference with my original thinking however.<\/p>\n<h3 id=\"code-vs-content\">Code vs. Content<\/h3>\n<p>I originally thought of &quot;using an HTML fragment&quot; as fetching content and parsing\nit as a DOM node, while the HTML module authors conceptualized the same thing as\n<em>importing<\/em> an HTML fragment into the JS module graph. This is likely because\nI&#39;m coming at this proposal from the perspective of &quot;using SSR&#39;d HTML in an\nexisting document&quot; whereas the original HTML imports proposal was focused on\n&quot;importing a web component&quot;. An SSR&#39;d fragment contains user data, while a\nstatic web component would receive user data as an input from other sources.<\/p>\n<p>I think this distinction ultimately comes down to whether you see an HTML\nfragment as &quot;content&quot; or &quot;code&quot;, the former would be fetched with a\nuser-controlled HTTP request, while the latter would be imported with module\nsemantics.<\/p>\n<p>Importing an HTML fragment has a lot of benefits. Most clearly to me it makes\nweb components much easier to use (<a href=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/#custom-elements\">more on that later<\/a>),\nhowever it also introduces some restrictions. For example, editing a tweet was\nimplemented by making a <code>POST<\/code> request to the server, which updates the database\nand responds with a newly rendered form of the tweet, all from one HTTP request:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> parseDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Implementation TBD...<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">MyEditableTweet<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">public<\/span> tweetId<span class=\"token operator\">!<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">async<\/span> <span class=\"token function\">onEditSaved<\/span><span class=\"token punctuation\">(<\/span>newContent<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ Post the edit to the server, which also returns<\/span>\n        <span class=\"token comment\">\/\/ the same tweet rendered with the new content.<\/span>\n        <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span>\n            <span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\/tweet\/edit?id=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span><span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>tweetId<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token string\">&amp;content=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>\n                <span class=\"token function\">encodeURIComponent<\/span><span class=\"token punctuation\">(<\/span>newContent<span class=\"token punctuation\">)<\/span><span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">,<\/span>\n            <span class=\"token punctuation\">{<\/span> method<span class=\"token operator\">:<\/span> <span class=\"token string\">'POST'<\/span> <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">,<\/span>\n        <span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">const<\/span> editedTweetTemplate <span class=\"token operator\">=<\/span>\n            <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Replace this DOM element with the new, edited tweet.<\/span>\n        <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">replaceWith<\/span><span class=\"token punctuation\">(<\/span>\n            editedTweetTemplate<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-editable-tweet'<\/span><span class=\"token punctuation\">,<\/span> MyEditableTweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>This approach isn&#39;t really possible using <code>import()<\/code> semantics, since you can&#39;t\n(and probably shouldn&#39;t) make a <code>POST<\/code> request when importing code. That would\nimply that user input dictates the structure of your application&#39;s executable\ncode, which is a big security issue. Of course, practically speaking it probably\nonly modifies the HTML content, while the JS and CSS is still likely authored by\na developer, it still requires trusting the server maintainer to do the right\nthing. We already do this for standard SSR&#39;d documents, so it&#39;s not that\ndifferent here, but again this is all about conceptualization. Do you see an\nHTML fragment as &quot;content&quot; or &quot;code&quot;? I think there&#39;s a valid debate to be had\nthere.<\/p>\n<p>A similar problem is that the &quot;HTML fragments as code&quot; concept assumes that HTML\nfragment URLs are stable and return consistent content for the lifetime of the\ndocument. For example, <code>import(&#39;\/tweet.js&#39;)<\/code> should always be consistent within\na single page load, but <code>import(&#39;\/tweet.html?id=1234&#39;)<\/code> for an SSR&#39;d fragment\nmay not because the tweet could be edited at any time. To support this,\nimporting the module twice should be able to return different results. Similar\nto the &quot;content&quot; vs. &quot;code&quot; distinction, should HTML fragments include SSR&#39;d\nuser data at all? If the returned fragment is a web component with a\nhand-authored template that gets used via CSR and has no user data, then the\nfragment looks a lot like &quot;code&quot; to me, and definitely isn&#39;t &quot;content&quot;. I get\nthe impression HTML modules, as the proposal currently thinks of them, are\nintended to be static, which changes the thought process here.<\/p>\n<p>Of course, even if we decide once and for all that HTML fragments are &quot;code&quot; and\nshould obey JS module import semantics, we can work around some of those\nlimitations and still <em>use<\/em> them as &quot;content&quot;. For the tweet edit use case, we\ncan break up the single HTTP <code>POST<\/code> request into a <code>POST<\/code> followed by an\n<code>import()<\/code> and use a cache busting query parameter to skip module caching.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/\/ An additional query parameter which gets incremented for<\/span>\n<span class=\"token comment\">\/\/ every dynamic import to ensure the requested URL is<\/span>\n<span class=\"token comment\">\/\/ *never* in the module cache.<\/span>\n<span class=\"token keyword\">let<\/span> cacheBust <span class=\"token operator\">=<\/span> <span class=\"token number\">0<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">MyEditableTweet<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">public<\/span> tweetId<span class=\"token operator\">!<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">async<\/span> <span class=\"token function\">onEditSaved<\/span><span class=\"token punctuation\">(<\/span>newContent<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token comment\">\/\/ Post the edit to the server, but we don't care<\/span>\n        <span class=\"token comment\">\/\/ about the response.<\/span>\n        <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span>\n            <span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\/tweet\/edit?id=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span><span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>tweetId<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token string\">&amp;content=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>\n                <span class=\"token function\">encodeURIComponent<\/span><span class=\"token punctuation\">(<\/span>newContent<span class=\"token punctuation\">)<\/span><span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">,<\/span>\n            <span class=\"token punctuation\">{<\/span> method<span class=\"token operator\">:<\/span> <span class=\"token string\">'POST'<\/span> <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">,<\/span>\n        <span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Make a separate HTTP request to import the<\/span>\n        <span class=\"token comment\">\/\/ newly-edited tweet fragment. Include the cache<\/span>\n        <span class=\"token comment\">\/\/ busting query parameter to skip the module cache.<\/span>\n        cacheBust<span class=\"token operator\">++<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">const<\/span> fragment<span class=\"token operator\">:<\/span> DocumentFragment <span class=\"token operator\">=<\/span>\n            <span class=\"token keyword\">await<\/span> <span class=\"token keyword\">import<\/span><span class=\"token punctuation\">(<\/span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">\/tweet.html?id=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>\n                    <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>tweetId<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token string\">&amp;cachebust=<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>cacheBust<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">)<\/span>\n                <span class=\"token punctuation\">.<\/span><span class=\"token function\">then<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">(<\/span>module<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> module<span class=\"token punctuation\">.<\/span>default<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">const<\/span> editedTweet <span class=\"token operator\">=<\/span>\n            fragment<span class=\"token punctuation\">.<\/span>firstElementChild<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ Replace this DOM element with the new, edited tweet.<\/span>\n        <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">replaceWith<\/span><span class=\"token punctuation\">(<\/span>editedTweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n\ncustomElements<span class=\"token punctuation\">.<\/span><span class=\"token function\">define<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'my-editable-tweet'<\/span><span class=\"token punctuation\">,<\/span> MyEditableTweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Treating HTML fragments as &quot;code&quot; instead of &quot;content&quot; may be the right answer,\nbut I think it&#39;s important for whatever mechanism this scheme uses to have solid\nsupport for SSR&#39;d HTML fragments. This would allow low-commitment\nHTML-over-the-wire architectures, which I think would have a lot of value for\nweb developers everywhere.<\/p>\n<p>A native means of using SSR&#39;d HTML fragments also has some interesting\nimplications for the broader web ecosystem which I want to call out more\nspecifically.<\/p>\n<h3 id=\"ecosystem\">Ecosystem<\/h3>\n<p>If something similar to HTML modules does eventually land, it would provide a\nunique way of embedding third-party content. Today, this is typically done via a\n<code>&lt;script \/&gt;<\/code> tag linking third-party sources with a custom element that renders\nthe UI. The limitation of this approach is that third-party libraries cannot\nprovide any meaningful SSR and require scripting for the most basic features\nwhich shouldn&#39;t require it.<\/p>\n<p>With full support of SSR&#39;d HTML fragments, a service could expose an API\nendpoint which returns a pre-rendered custom element and encapsulates its own\nscripts and styles. Imagine real Twitter providing a URL that returns an SSR&#39;d\ntweet with styling in an HTML fragment. All you have to do is append it wherever\nyou want on the page. Their documentation would just consist of an example which\nlooks like:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">const<\/span> fragment <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token keyword\">import<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/tweet.html?id=1234'<\/span><span class=\"token punctuation\">)<\/span>\n    <span class=\"token punctuation\">.<\/span><span class=\"token function\">then<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">(<\/span>module<span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> module<span class=\"token punctuation\">.<\/span>default<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> tweet <span class=\"token operator\">=<\/span>\n    fragment<span class=\"token punctuation\">.<\/span>firstElementChild<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\ndocument<span class=\"token punctuation\">.<\/span>body<span class=\"token punctuation\">.<\/span><span class=\"token function\">appendChild<\/span><span class=\"token punctuation\">(<\/span>tweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Twitter in particular is cool because it does not actually require scripting\ncapabilities. An SSR&#39;d tweet does not need any JavaScript, so a web site\ncould embed a tweet with a CSP directive which blocks scripting capabilities\nfrom Twitter and further protects users more than possible today.<\/p>\n<p>Taking this a step further, it&#39;s unfortunate that the approach requires\nJavaScript at all. What if we could do this directly in HTML? Imagine a new\n<code>&lt;embed \/&gt;<\/code> element, which takes a URL, fetches it with a <code>GET<\/code> request, parses\nthe result as an HTML fragment, and inserts it directly into the DOM. That means\nyou could write:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>embed<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet?id=1234<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token punctuation\">\/><\/span><\/span>\n<\/code><\/pre><p>And the browser would automatically fetch <code>\/tweet?id=1234<\/code> and append the\nresult, no custom JS required! You&#39;d end up with:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>embed<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet?id=1234<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>template<\/span> <span class=\"token attr-name\">shadowroot<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>open<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>link<\/span> <span class=\"token attr-name\">rel<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>stylesheet<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">href<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.css<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span>\n            <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>Here is a tweet!<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>span<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>template<\/span><span class=\"token punctuation\">><\/span><\/span>\n        <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>my-tweet<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>embed<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>I think this is incredibly powerful since it opens up all kinds of cool embed\nuse cases. Imagine pasting a one line <code>&lt;embed \/&gt;<\/code> tag into a markdown file and\nhaving it <em>just work<\/em> in a secure, performant, and user-friendly fashion. Again,\nthis does look a lot like HTML imports, but I think mixing the approach with\nSSR&#39;d fragments makes this a much more powerful embed strategy.<\/p>\n<p>The alternative approach to accomplish this today is to embed an <code>&lt;iframe \/&gt;<\/code>\nwhich links to a Twitter page that renders the tweet. This has the advantage of\ntruly sandboxing the embed content, which can be very useful. However, it is\nalso far less performant and harder to use.<\/p>\n<p>True story: That tweet at the top of the page was originally rendered with\n<a href=\"https:\/\/developer.twitter.com\/en\/docs\/twitter-for-websites\/embedded-tweets\/overview\" target=\"_blank\">Twitter's embed API<\/a>\nwhich uses an <code>&lt;iframe \/&gt;<\/code>. This one embed:<\/p>\n<ul>\n<li>Made 22 out of 43 network requests for the page (13 of which were JS files).<\/li>\n<li>Downloaded 1.6 MB out of 2.6 MB of resources for the page.<\/li>\n<li>Painted at the ~1 sec mark when largest contentful paint ocurred at 87 ms.<\/li>\n<li>Appears to have downloaded React (this page does not otherwise use React).<\/li>\n<\/ul>\n<p>Now I am by no means a web performance expert and this is just one example. I\nalso want to avoid picking on Twitter too much here, they are by no means the\nworst offender. The point is that this is a significant weight for a fairly\nsimple use case, and it bothered me enough to implement my own version of the\ntweet component. SSR-ing an HTML fragment could be a much lighter weight and\neasier to use alternative to an <code>&lt;iframe \/&gt;<\/code> embed. I think this could have a\nhuge impact on embedded third-party content.<\/p>\n<p>Including HTML modules (in an SSR-compatible way) with <code>&lt;embed \/&gt;<\/code> as official\nadditions to the web standard could have significant impact for embedding\nthird-party content in addition to the low-commitment HTML-over-the-wire\narchitecture discussed earlier.<\/p>\n<p>Edit: I realized later that one can prototype this <code>&lt;embed \/&gt;<\/code> tag as a custom\nelement. <a href=\"https:\/\/github.com\/dgp1130\/html-fragments-demo\/blob\/blog-post\/client\/em-bed.ts\" target=\"_blank\">So I did<\/a>,\nand it works\n<a href=\"https:\/\/github.com\/dgp1130\/html-fragments-demo\/blob\/blog-post\/client\/embedded.html#L11\" target=\"_blank\">just as smoothly as I wanted it to<\/a>.<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/4-embed.avif\" type=\"image\/avif\" width=\"1120\" height=\"751\" \/>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/4-embed.webp\" type=\"image\/webp\" width=\"1120\" height=\"751\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/4-embed.png\" alt=\"A screenshot of a page title with the header &quot;Embedding a Tweet&quot; which includes a single tweet along with an open DevTools Network tab showing that the tweet was fetched as an HTML fragment.\" width=\"1120\" height=\"751\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<p>So that&#39;s the interesting part of this blog post and you can stop reading now. I\nalso have a <a href=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/\">follow-up post<\/a> which <em>streams<\/em>\nHTML fragments. There were a lot of unexpected nuances and challenges with\nmaking this approach streamable, so check it out!<\/p>\n<p>However, I never really explained how my implementation of <code>parseDomFragment()<\/code>\nworks. I encountered a few surprising edge cases and learned some interesting\ntidbits about the web specification, so if that is your kind of thing, keep\nreading.<\/p>\n<h2 id=\"implementation\">Implementation<\/h2>\n<p>It turns out that <code>parseDomFragment()<\/code> is only about 40 lines of meaningful\ncode. Fundamentally, all it does is call:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">new<\/span> <span class=\"token class-name\">DOMParser<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">parseFromString<\/span><span class=\"token punctuation\">(<\/span>\n    <span class=\"token keyword\">await<\/span> response<span class=\"token punctuation\">.<\/span><span class=\"token function\">text<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">,<\/span>\n    <span class=\"token string\">'text\/html'<\/span><span class=\"token punctuation\">,<\/span>\n<span class=\"token punctuation\">)<\/span>\n<\/code><\/pre><p>However, there are a couple edge cases it needs to handle. The\n<a href=\"https:\/\/github.com\/dgp1130\/html-fragments-demo\/blob\/blog-post\/client\/dom.ts\" target=\"_blank\">full TypeScript source is here<\/a>\nif you just want to get on with your life.\n<a href=\"https:\/\/gist.github.com\/dgp1130\/1283773eb5890fb3cf59005892231211\" target=\"_blank\">JS is also here<\/a>\nif you are too lazy to run <code>tsc<\/code> as well. With that out of the way, let&#39;s dive\nin to weird edge cases!<\/p>\n<h3 id=\"loading-scripts\">Loading Scripts<\/h3>\n<p>My initial implementation simply did not execute any client-side JavaScript.<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/5-missing-script.avif\" type=\"image\/avif\" width=\"1141\" height=\"559\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/5-missing-script.png\" alt=\"A screenshot of the Twitter demo application with Chrome DevTools open. The application itself looks identical to the first screenshot, with two short demo tweets. Chrome DevTools shows the network tab. Two of these requests are highlighted, the first for `\/tweet?id=1234` the second for `\/tweet.css`. The highlight is labeled &quot;No tweet.js?&quot;, indicating there is no request for `\/tweet.js` as would be expected.\" width=\"1141\" height=\"559\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<p>I looked up the\n<a href=\"https:\/\/www.w3.org\/TR\/DOM-Parsing\/\" target=\"_blank\"><code>DOMParser spec<\/code><\/a> and found that\nscripting is\n<a href=\"https:\/\/www.w3.org\/TR\/DOM-Parsing\/#:~:text=script%20elements%20get%20marked%20unexecutable%20and%20the%20contents%20of%20noscript%20get%20parsed%20as%20markup.\" target=\"_blank\">explicitly disabled<\/a>!<\/p>\n<blockquote>\n<p>The <code>parseFromString(str, type)<\/code> method must run these steps, depending on type:<\/p>\n<ul>\n<li><p><code>&quot;text\/html&quot;<\/code> - Parse <code>str<\/code> with an HTML parser, and return the newly created document.<\/p>\n<p><strong>The scripting flag must be set to &quot;disabled&quot;.<\/strong><\/p>\n<\/li>\n<\/ul>\n<blockquote>\n<p>NOTE<\/p>\n<p><code>script<\/code> elements get marked unexecutable and the contents of <code>noscript<\/code> get parsed as markup.<\/p>\n<\/blockquote>\n<\/blockquote>\n<p>This seemed like a non-starter, but there is a workaround. We don&#39;t actually\nwant <code>DOMParser<\/code> to execute scripts. After all, it generates a new\n<code>DocumentFragment<\/code> that will get wrapped in an <code>HTMLTemplateElement<\/code>, so it will\nnot be directly rendered to the user anyways. We only want the <em>cloned<\/em> HTML\nwhich is actually inserted into the active document to execute scripts.<\/p>\n<p>We can work around this by manually cloning any <code>&lt;script \/&gt;<\/code> tags and replacing\nthem in the <code>DocumentFragment<\/code>. This keeps the semantics the same while\neffectively making the browser &quot;forget&quot; that they were originally parsed in a\ncontext which had scripting disabled.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">function<\/span> <span class=\"token function\">replaceScripts<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token operator\">:<\/span> Element<span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token keyword\">void<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> scripts <span class=\"token operator\">=<\/span> <span class=\"token builtin\">Array<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">from<\/span><span class=\"token punctuation\">(<\/span>el<span class=\"token punctuation\">.<\/span><span class=\"token function\">querySelectorAll<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'script'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">for<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> oldScript <span class=\"token keyword\">of<\/span> scripts<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">const<\/span> newScript <span class=\"token operator\">=<\/span> document<span class=\"token punctuation\">.<\/span><span class=\"token function\">createElement<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'script'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">for<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> name <span class=\"token keyword\">of<\/span> oldScript<span class=\"token punctuation\">.<\/span><span class=\"token function\">getAttributeNames<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n            <span class=\"token keyword\">const<\/span> oldAttr <span class=\"token operator\">=<\/span> oldScript<span class=\"token punctuation\">.<\/span><span class=\"token function\">getAttribute<\/span><span class=\"token punctuation\">(<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token operator\">!<\/span><span class=\"token punctuation\">;<\/span>\n            newScript<span class=\"token punctuation\">.<\/span><span class=\"token function\">setAttribute<\/span><span class=\"token punctuation\">(<\/span>name<span class=\"token punctuation\">,<\/span> oldAttr<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token punctuation\">}<\/span>\n        newScript<span class=\"token punctuation\">.<\/span>textContent <span class=\"token operator\">=<\/span> oldScript<span class=\"token punctuation\">.<\/span>textContent<span class=\"token punctuation\">;<\/span>\n\n        oldScript<span class=\"token punctuation\">.<\/span><span class=\"token function\">replaceWith<\/span><span class=\"token punctuation\">(<\/span>newScript<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>This works and makes the browser load JavaScript as expected! Except it works a\nlittle too well...<\/p>\n<h3 id=\"duplicated-scripts\">Duplicated Scripts<\/h3>\n<p>At this point I got some strange errors, and I eventually narrowed down the\nproblem to:<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/6-double-script.avif\" type=\"image\/avif\" width=\"1141\" height=\"559\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/6-double-script.png\" alt=\"A screenshot of the demo Twitter application with Chrome DevTools opened to the console panel. The console shows a message &quot;(2) Running tweet.js...&quot; followed by an error: &quot;Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': The name 'my-tweet' has already been used with this registry&quot;.\" width=\"1141\" height=\"559\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<p>Note the &quot;2&quot; by the first log statement along with &quot;&#39;my-tweet&#39; has already been\nused with this registry&quot;, I was loading the same JavaScript file twice! This was\nvery confusing to me, since the same script tag was just being duplicated in two\ndifferent HTML fragments. Each one contained:<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>Normally, that works just fine. If you duplicate a <code>&lt;script \/&gt;<\/code> tag in an HTML\ndocument it will only fetch and execute it once.<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/foo.js<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/foo.js<span class=\"token punctuation\">\"<\/span><\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>I ignored the problem for a while and ended up solving it by accident. I wanted\nto share the <code>parseDomFragment()<\/code> function and was too lazy to add a bundler, so\nI used\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Guide\/Modules\" target=\"_blank\">native ESM<\/a>\nand found that the problem just went away! It turns out that simply adding\n<code>type=&quot;module&quot;<\/code> fixed the bug, but why?<\/p>\n<pre><code class=\"language-html\"><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;<\/span>script<\/span> <span class=\"token attr-name\">src<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>\/tweet.js<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">type<\/span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=<\/span><span class=\"token punctuation\">\"<\/span>module<span class=\"token punctuation\">\"<\/span><\/span> <span class=\"token attr-name\">async<\/span><span class=\"token punctuation\">><\/span><\/span><span class=\"token script\"><\/span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;\/<\/span>script<\/span><span class=\"token punctuation\">><\/span><\/span>\n<\/code><\/pre><p>After some spelunking in the HTML spec, I believe the difference comes down to\ncaching. Fetching a &quot;classic&quot; script\n<a href=\"https:\/\/html.spec.whatwg.org\/multipage\/webappapis.html#fetch-a-classic-script\" target=\"_blank\">just makes the HTTP request<\/a>,\nbut fetching a &quot;module&quot; script\n<a href=\"https:\/\/html.spec.whatwg.org\/multipage\/webappapis.html#fetch-a-single-module-script\" target=\"_blank\">checks a module cache first<\/a>.\nI believe this cache is what stops the second <code>&lt;script type=&quot;module&quot; \/&gt;<\/code> tag\nfrom triggering another network request and execution.<\/p>\n<p>I am not totally clear on why duplicate classic scripts loaded in this manner\nare executed multiple times, when traditionally duplicated classic scripts are\nstill executed only once. If you have any idea,\n<a href=\"https:\/\/twitter.com\/develwoutacause\/\" target=\"_blank\">let me know<\/a>!<\/p>\n<h3 id=\"loading-styles\">Loading Styles<\/h3>\n<p>I actually lied a little bit in one of my earlier screenshots, did you catch it?\nLet me show you a more accurate image, does anything stand out a little weird?<\/p>\n<p><picture>\n    <source srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/7-double-style.avif\" type=\"image\/avif\" width=\"1081\" height=\"680\" \/>\n    <img srcset=\"https:\/\/blog.dwac.dev\/posts\/html-fragments\/demos\/7-double-style.png\" alt=\"A screenshot of the Twitter demo application with Chrome DevTools open to the network tab. In the network, there are two requests for tweet fragments, the first includes a request for `\/tweet?id=1234`, followed by `\/tweet.css` and `\/tweet.js`. The second includes a request for `\/tweet?id=4321` and is also followed by a duplicate request to `\/tweet.css`.\" width=\"1081\" height=\"680\" decoding=\"async\" loading=\"lazy\" \/>\n<\/picture><\/p>\n<p><code>\/tweet.css<\/code> got downloaded twice, what gives!? It seems that much like\n<code>&lt;script \/&gt;<\/code> tags, putting the same stylesheet in the document twice actually\nfetches it multiple times. The simplest solution I found was to cache the\nstylesheet via\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/Headers\/Cache-Control\" target=\"_blank\"><code>Cache-Control<\/code><\/a>.\nThis was enough to avoid re-requesting the file, though it seems weird to me\nthat it is necessary to do this in the first place. I think it also evaluates\nthe stylesheet and applies it to the page multiple times, which doesn&#39;t seem\nideal, but it&#39;s good enough for this demo.<\/p>\n<h3 id=\"declarative-shadow-dom\">Declarative Shadow DOM<\/h3>\n<p>One other thing that didn&#39;t work out of the box is Declarative Shadow DOM. The\nHTML fragment would be appended to the document correctly but not render any\nchildren under the shadow root. This is because Declarative Shadow DOM is\ndefined as a &quot;parser-only&quot; feature, meaning you cannot append a new element with\nDeclarative Shadow DOM to an existing <code>Document<\/code>, the contents of the template\nwill just be ignored!<\/p>\n<p>Fortunately, <code>DOMParser.prototype.parseFromString<\/code> has an extra option in\nChrome, <code>includeShadowRoots<\/code>, which does exactly what we need. This makes the\nresulting fragment &quot;just work&quot; the way we expect:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">new<\/span> <span class=\"token class-name\">DOMParser<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">parseFromString<\/span><span class=\"token punctuation\">(<\/span>html<span class=\"token punctuation\">,<\/span> <span class=\"token string\">'text\/html'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">{<\/span>\n    includeShadowRoots<span class=\"token operator\">:<\/span> <span class=\"token boolean\">true<\/span>\n<span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p><a href=\"https:\/\/web.dev\/declarative-shadow-dom\/#parser-only\" target=\"_blank\">This post<\/a> has a great\nexplanation of Declarative Shadow DOM&#39;s parser-only nature. The caveat here is\nthat this option is not present\n<a href=\"https:\/\/www.w3.org\/TR\/DOM-Parsing\/#the-domparser-interface\" target=\"_blank\">in the spec<\/a>.\nThough Declarative Shadow DOM isn&#39;t fully adopted in the spec either and only\nsupported by Chromium right now anyways, so \ud83e\udd37\u200d\u2642\ufe0f.<\/p>\n<p>The motivation for this flag seems to be to avoid <a href=\"https:\/\/github.com\/whatwg\/dom\/issues\/831#issuecomment-718157132\" target=\"_blank\">XSS vulnerabilities in\nexisting HTML sanitizers that do not know about Declarative Shadow DOM<\/a>.\nSo as long as you are using up-to-date sanitizers, I believe this should be safe\nto do.<\/p>\n<h3 id=\"custom-elements\">Custom elements<\/h3>\n<p>For this example, I did not want to use a CSR framework, so I used native custom\nelements. However, that introduces typical rough edges the community commonly\ncomplains about. Constructing an element in memory is awkward and TypeScript\ndoes not like the lack of strict property initialization in the constructor.\nHydrating from SSR&#39;d content is a bit awkward as well. There are plenty of small\ncustom element libraries (ie. <a href=\"https:\/\/lit.dev\/\" target=\"_blank\">Lit Element<\/a>) which can make\nthe authoring experience much smoother, however I believe many are still lacking\na solid hydration story given how new Declarative Shadow DOM is.<\/p>\n<p>The more annoying issue IMHO is that lazy loaded DOM nodes do not fetch scripts\nuntil <em>after<\/em> they are inserted into the DOM. This is good for laziness and the\nperformance benefits that brings but when combined with a custom element it gets\nvery awkward. The main problem is that an inserted DOM node is immediately\nvisible and interactable to the user but the custom element definition has not\nbeen downloaded and the element itself is not upgraded yet. That means you end\nup with scenarios like this:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/\/ my-editable-tweet.ts<\/span>\n\n<span class=\"token keyword\">export<\/span> <span class=\"token keyword\">class<\/span> <span class=\"token class-name\">MyEditableTweet<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/** Focus on the internal input element. *\/<\/span>\n    <span class=\"token keyword\">public<\/span> <span class=\"token function\">focus<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>shadowRoot<span class=\"token operator\">!<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">querySelector<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'input'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">!<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">focus<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><pre><code class=\"language-typescript\"><span class=\"token comment\">\/\/ my-tweet.ts<\/span>\n\n<span class=\"token keyword\">import<\/span> <span class=\"token keyword\">type<\/span> <span class=\"token punctuation\">{<\/span> MyEditableTweet <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/my-editable-tweet'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">export<\/span> <span class=\"token keyword\">class<\/span> <span class=\"token class-name\">MyTweet<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">HTMLElement<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">async<\/span> <span class=\"token function\">onEdit<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">Promise<\/span><span class=\"token operator\">&lt;<\/span><span class=\"token keyword\">void<\/span><span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/editable-tweet'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">const<\/span> template <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        <span class=\"token keyword\">const<\/span> content <span class=\"token operator\">=<\/span>\n            template<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token comment\">\/\/ WRONG! `MyEditableTweet` is lazy loaded *after*<\/span>\n        <span class=\"token comment\">\/\/ it is first inserted into the document. On first<\/span>\n        <span class=\"token comment\">\/\/ edit, it has not been downloaded yet, so the<\/span>\n        <span class=\"token comment\">\/\/ element is not yet upgraded and none of its<\/span>\n        <span class=\"token comment\">\/\/ functionality exists.<\/span>\n        <span class=\"token keyword\">const<\/span> editableTweet <span class=\"token operator\">=<\/span> content <span class=\"token keyword\">as<\/span> MyEditableTweet<span class=\"token punctuation\">;<\/span>\n\n        <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">replaceWith<\/span><span class=\"token punctuation\">(<\/span>editableTweet<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n        editableTweet<span class=\"token punctuation\">.<\/span><span class=\"token function\">focus<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ ERR: `focus` is `undefined`.<\/span>\n    <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>You can use\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/CustomElementRegistry\/whenDefined\" target=\"_blank\"><code>customElements.whenDefined('my-editable-tweet')<\/code><\/a>\nto wait for the script to load and then be confident that the node has been\nupgraded. However that is an asynchronous operation, and in this particular case\nthe user could have moved on to do other things so it would be inappropriate to\nsteal focus, making an &quot;auto-focus on edit&quot; feature difficult to implement.<\/p>\n<p>The core problem here is that the first time an HTML fragment with a custom\nelement is inserted into the DOM, the element&#39;s implementation is <em>not<\/em> yet\nexecuted and you need to wait for it. However, the second time that HTML\nfragment is inserted, the element&#39;s implementation will <em>already<\/em> have been\nexecuted, so your code needs to be compatible with both timings.<\/p>\n<p>HTML modules and treating fragments as &quot;code&quot; instead of &quot;content&quot; actually\nfixes this problem.\n<a href=\"https:\/\/github.com\/WICG\/webcomponents\/blob\/gh-pages\/proposals\/html-modules-explainer.md#specifying-an-html-modules-exports\" target=\"_blank\">It proposes<\/a>\nexecuting all <code>&lt;script \/&gt;<\/code> tags in the HTML fragment and merging their exports\ntogether as the result of the <code>import()<\/code>. This means that a web component\ndefinition included in an HTML fragment will always be evaluated <em>before<\/em> the\nassociated DOM element is accessible.<\/p>\n<p><a href=\"https:\/\/github.com\/WICG\/webcomponents\/blob\/gh-pages\/proposals\/html-modules-explainer.md#example-custom-element-definition-in-an-html-module\" target=\"_blank\">This example<\/a>\ndemonstrates how a custom element can be easily defined and loaded. Treating\nfragments as code definitely has some benefits in this regard and makes web\ncomponents much easier to use.<\/p>\n<h3 id=\"template-foot-guns\">Template foot-guns<\/h3>\n<p>While implementing this, I also managed to shoot myself in the foot a number of\ntimes using templates. The easiest mistake to make is to forget <code>.content<\/code> like\nso:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> parseDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/foo'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> template <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ Wrong: `element1` is an `HTMLTemplateElement`, which is<\/span>\n<span class=\"token comment\">\/\/ inert when inserted into the document.<\/span>\n<span class=\"token keyword\">const<\/span> element1 <span class=\"token operator\">=<\/span> template<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ Right: `element2` is a clone of the template's *content*.<\/span>\n<span class=\"token keyword\">const<\/span> element2 <span class=\"token operator\">=<\/span> template<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Another easy mistake is to assume that the content is the custom element you\nwant when it is actually a <code>DocumentFragment<\/code> which <em>contains<\/em> your custom\nelement.\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Element\/firstElementChild\" target=\"_blank\"><code>Element.prototype.firstElementChild<\/code><\/a>\nis an easy way of accessing the instantiated custom element.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> parseDomFragment <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'.\/dom.js'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">const<\/span> res <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">fetch<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'\/tweet?id=1234'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> template <span class=\"token operator\">=<\/span> <span class=\"token keyword\">await<\/span> <span class=\"token function\">parseDomFragment<\/span><span class=\"token punctuation\">(<\/span>res<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> instance <span class=\"token operator\">=<\/span> template<span class=\"token punctuation\">.<\/span>content<span class=\"token punctuation\">.<\/span><span class=\"token function\">cloneNode<\/span><span class=\"token punctuation\">(<\/span><span class=\"token boolean\">true<\/span> <span class=\"token comment\">\/* deep *\/<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ WRONG: `instance` is actually a `DocumentFragment`.<\/span>\n<span class=\"token keyword\">const<\/span> tweet1 <span class=\"token operator\">=<\/span> instance <span class=\"token keyword\">as<\/span> MyTweet<span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ RIGHT: `instance` *contains* a `&lt;my-tweet \/>` element.<\/span>\n<span class=\"token keyword\">const<\/span> fragment <span class=\"token operator\">=<\/span> instance <span class=\"token keyword\">as<\/span> DocumentFragment<span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> tweet2 <span class=\"token operator\">=<\/span> fragment<span class=\"token punctuation\">.<\/span>firstElementChild <span class=\"token keyword\">as<\/span> MyTweet<span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>TypeScript helps for many issues like these, but a lot of the types overlap with\neach other and do not give errors in many invalid situations. One annoying edge\ncase for TypeScript specifically is that\n<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Node\/cloneNode\" target=\"_blank\"><code>DocumentFragment.prototype.cloneNode()<\/code><\/a>\nreturns <code>Node<\/code>, requiring an explicit cast to <code>DocumentFragment<\/code>, and giving a\nkey opportunity to mistakenly cast to its child node. Ideally,\n<code>DocumentFragment.prototype.cloneNode()<\/code> would return a <code>DocumentFragment<\/code> type.\nApparently making this return value generic is\n<a href=\"https:\/\/github.com\/microsoft\/TypeScript\/issues\/283\" target=\"_blank\">more complicated than it seems<\/a>\non the surface.<\/p>\n<p>All these challenges lead to my desire to make this a proper part of the web\nspecification. Designing HTML imports intentionally for this use case would give\nan opportunity to fix some of these confusing aspects.<\/p>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>When I started experimenting with a native HTML-over-the-wire implementation, I\nwas just curious how complex of a problem it was. What surprised me was how much\nis already given by the platform natively. While I cannot recommend this\napproach until it becomes an official standard, I&#39;m excited by the direction of\nHTML modules and hope we can find a path to using them with SSR. Doing so would\nenable low-commitment architectures, where an application can be predominantly\nSSR&#39;d while still supporting its occasional reactive use case. All of this can\nbe done without being forced to commit to a CSR framework, duplicate logic\nacross CSR and SSR, or use a hybrid rendering solution. It also comes with major\nbenefits for third-party embed use cases, making such content more secure and\nusable.<\/p>\n<p>I think there is a lot of potential here, and I hope web developers get the\nopportunity to fully explore it.<\/p>\n<p><strong>Edit<\/strong>: If you got this far, you should <em>definitely<\/em> check out\n<a href=\"https:\/\/blog.dwac.dev\/posts\/streamable-html-fragments\/\">the sequel to this post<\/a> on\n<em>streaming<\/em> HTML fragments. Lost of interesting nuances, challenges, and &quot;fun&quot;\nbugs along the way.<\/p>\n"},{"title":"Construct Better","link":{"@attributes":{"href":"https:\/\/blog.dwac.dev\/posts\/ctor\/"}},"updated":"2022-02-13T19:00:00Z","id":"https:\/\/blog.dwac.dev\/posts\/ctor\/","content":"<h1 id=\"construct-better\">Construct Better<\/h1>\n<time datetime=\"2022-02-13T19:00:00.000Z\" class=\"timestamp\">February 13, 2022<\/time><p>Constructors are weird. No, seriously, have you ever taken a moment to\n<em>really<\/em> think about them? Why they work the way they do? You probably learned\nabout constructors in school or on some online course and just accepted that is\nthe way objects are created. At some point you probably heard about the\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Factory_method_pattern\" target=\"_blank\">factory pattern<\/a> and use\nthat from time to time. For the most part, the development community has largely\naccepted what a constructor looks like and how it works. But are constructors\nreally a solved problem? Or have we just plastered over the issues that come\nwith them via unnecessary workarounds?<\/p>\n<h2 id=\"limitations-of-constructors\">Limitations of Constructors<\/h2>\n<p>Constructors, by design, have a number of restrictions and constraints which are\napplied to them. While this varies across languages, consider the number of\nthings constructors generally <em>cannot<\/em> do:<\/p>\n<ul>\n<li>Return <code>null<\/code>.<\/li>\n<li>Be asynchronous.<\/li>\n<li>Return a subclass.<\/li>\n<li>Return an already existing object.<\/li>\n<\/ul>\n<p>Many languages also use the <code>new<\/code> keyword as an operator to invoke a\nconstructor, however the act of constructing a new object is entirely an\nimplementation detail. Whether a function returns a new instance of an object or\nan existing one is mostly irrelevant to callers. However, if that function is\nimplemented as a public constructor, then it leaks the implementation detail of\nconstructing a new object. It means the function is now forced into the above\nrestrictions and cannot opt-out of them without breaking its API contract.<\/p>\n<p>Factories solve a lot of these problems, and countless engineers have written\n&quot;best practices&quot; docs and books espousing the factory pattern. However factories\nhave their own limitations. They do not play well with subclassing and\ninheritance in general, because subclasses cannot extend an object returned by\nanother factory. Consider the following example:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Foo<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">protected<\/span> <span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">public<\/span> name<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token comment\">\/\/ Factory to hide the implementation detail of finding a<\/span>\n  <span class=\"token comment\">\/\/ user's name.<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">fromId<\/span><span class=\"token punctuation\">(<\/span>id<span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Foo <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> name <span class=\"token operator\">=<\/span> <span class=\"token function\">getNameFromId<\/span><span class=\"token punctuation\">(<\/span>id<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Foo<\/span><span class=\"token punctuation\">(<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Bar<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Foo<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> <span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span>name<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token keyword\">public<\/span> age<span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">super<\/span><span class=\"token punctuation\">(<\/span>name<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">fromId<\/span><span class=\"token punctuation\">(<\/span>id<span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Bar <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Need to repeat `getNameFromId()` here, can't compose<\/span>\n    <span class=\"token comment\">\/\/ `Foo.fromId()` like I want to without getting hacky.<\/span>\n    <span class=\"token keyword\">const<\/span> name <span class=\"token operator\">=<\/span> <span class=\"token function\">getNameFromId<\/span><span class=\"token punctuation\">(<\/span>id<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">const<\/span> age <span class=\"token operator\">=<\/span> <span class=\"token function\">getAgeFromId<\/span><span class=\"token punctuation\">(<\/span>id<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Bar<\/span><span class=\"token punctuation\">(<\/span>name<span class=\"token punctuation\">,<\/span> age<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Factories simply cannot compose each other in a useful fashion and superclasses\nleak implementation details into subclasses, with no easy or consistent\nworkaround.<\/p>\n<p>Factories also do not work well with frameworks which often need hooks into\nconstructors or need to own them entirely and have to implement their own\nlifecycle methods instead (looking at you,\n<a href=\"https:\/\/angular.io\/api\/core\/OnInit\" target=\"_blank\"><code>ngOnInit()<\/code><\/a>).<\/p>\n<p>These limitations introduce awkward constraints on code which limit options\navailable to developers when they inevitably need to change that code. Beyond\nthese feature limitations, the general awkwardness of using constructors can be\nbest shown by looking closely at the syntax and the exceptions that are required\nto support constructors.<\/p>\n<h2 id=\"syntactical-exceptions\">Syntactical Exceptions<\/h2>\n<p>Consider this trivial <a href=\"https:\/\/www.typescriptlang.org\/\" target=\"_blank\">TypeScript<\/a> class\nmodeling everyone&#39;s\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/The_Simpsons\" target=\"_blank\">favorite dysfunctional family<\/a>.\nNote that while I am picking on TypeScript here and languages do vary, many of\nthese points apply to <em>most<\/em> general purpose object-oriented languages:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">readonly<\/span> firstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span>firstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">super<\/span><span class=\"token punctuation\">(<\/span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${<\/span>firstName<span class=\"token interpolation-punctuation punctuation\">}<\/span><\/span><span class=\"token string\"> Simpson<\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>firstName <span class=\"token operator\">=<\/span> firstName<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Let me list out of the exceptions developers need to keep in mind when writing\nconstructors in TypeScript:<\/p>\n<p>First, <strong>constructors do <em>not<\/em> have a declared return type<\/strong>, it is implied to\nbe the same class. When else do you not specify a return type to what is clearly\nintended to look like a function?<\/p>\n<p>Second, <strong>constructors are declared with the special name <code>constructor()<\/code><\/strong>.\nOther languages commonly use the same name as their class.  When else does the\nname of something affect its behavior?<\/p>\n<p>Third, <strong><code>super()<\/code> <em>must<\/em> be executed before <code>this<\/code> can be used<\/strong>. You also\ncannot use <code>this<\/code> in the <code>super()<\/code> expression itself. When else does a\nparticular variable come into scope part way through a block?<\/p>\n<p>Fourth, <strong>code which does not reference <code>this<\/code> <em>can<\/em> come before <code>super()<\/code><\/strong> in\nTypeScript (unlike many other languages), <strong>but doing so means you <a href=\"https:\/\/github.com\/microsoft\/TypeScript\/issues\/945#issuecomment-60419937\" target=\"_blank\">cannot use\nfield initializers, parameter properties, or native private fields<\/a><\/strong>.\nIf you want those features, <code>super()<\/code> <strong>must<\/strong> be the first statement of your\nconstructor. This means that the following is not ok, despite the fact that the\nonly meaningful change is introducing a temporary variable, it is effectively\nthe same thing!<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">readonly<\/span> firstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token comment\">\/\/ Any field initializer means `super()` must come first!<\/span>\n  <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">readonly<\/span> age<span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token operator\">|<\/span><span class=\"token keyword\">null<\/span> <span class=\"token operator\">=<\/span> <span class=\"token keyword\">null<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span>firstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> fullName <span class=\"token operator\">=<\/span> firstName <span class=\"token operator\">+<\/span> <span class=\"token string\">' Simpson'<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">super<\/span><span class=\"token punctuation\">(<\/span>fullName<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ ERR: `super()` must be the first statement.<\/span>\n    <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>firstName <span class=\"token operator\">=<\/span> firstName<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>How often have you made a <code>static<\/code> function just to perform some arbitrary\ncomputation in order to inline it into a <code>super()<\/code> call?<\/p>\n<p>Fifth, <strong>you normally cannot assign to a <code>readonly<\/code> variable, but in\nconstructors you can<\/strong>! However this can only be done if the compiler is sure\nthat the variable is only assigned once. How often have you turned an <code>if<\/code>\nstatement into a ternary expression or a <code>static<\/code> function call in order to get\nthings to compile?<\/p>\n<p>Finally, <strong>constructors do not require a <code>return;<\/code> statement<\/strong>, because a\n<code>return this;<\/code> is implied. However, if you wish to return early, you should use\n<code>return;<\/code> without <code>this<\/code>, as if it were a <code>void<\/code> function, but it is not a\n<code>void<\/code> function because it implicitly returns a new class instance. Wat?<\/p>\n<p>JavaScript throws another wrench into this because <code>return &#39;foo&#39;;<\/code> will actually\nuse <code>&#39;foo&#39;<\/code> instead of the constructed class. Except <code>return undefined;<\/code> is the\nsame as <code>return;<\/code>, so the constructed class will be used instead. It also means\nthat calling <code>new Simpson()<\/code> may not <em>actually<\/em> create a new <code>Simpson<\/code> object,\nso that keyword can just lie sometimes.<\/p>\n<p>Most of these restrictions have valid reasons for existing. It makes logical\nsense that <code>this<\/code> cannot be used before <code>super()<\/code> is called, or else it would\nnot represent anything meaningful. However the language has to bend over\nbackwards for a syntax that kinda-sorta makes sense with these restrictions.<\/p>\n<p>Most developers just get used to these restrictions and do not really think\nabout them, but recall when you first learned constructors, or if you have ever\nhad to teach them to someone else. There is so much unnecessary complexity for\nsomething that should be as simple as &quot;make an object and return it&quot;.<\/p>\n<p>Many languages fix specific parts of these issues:<\/p>\n<ul>\n<li>Dart has named constructors.<\/li>\n<li>C# uses a <code>: base()<\/code> syntax to pull the <code>super()<\/code> call out of the body of the\nfunction, which avoids the scope problems of <code>this<\/code>.<\/li>\n<li>C++ uses initializer lists to set <code>const<\/code> fields, so <code>this-&gt;constField = ...<\/code>\nis never valid as would be expected.<\/li>\n<li>Kotlin omits the <code>new<\/code> operator entirely, making object construction a private\nimplementation detail.<\/li>\n<li>Python also omits the <code>new<\/code> operator and has <code>__new__<\/code>, which allows a class\nto return an unrelated value instead of constructing a new object every time.<\/li>\n<\/ul>\n<p>These languages show that many of these individual issues can be addressed with\nbetter syntax, but a lot of them are also integral to the way constructors are\nconceptualized. So what is wrong with the core concept that leads to all this\nweirdness?<\/p>\n<h2 id=\"constructor-flaws\">Constructor Flaws<\/h2>\n<p>I see three root mistakes that lead to this strange syntax and behavior:<\/p>\n<h3 id=\"constructors-are-a-user-level-construct\">Constructors are a user-level construct<\/h3>\n<p>In most OO languages, constructors are hand-written by developers for classes\nthey own. Some languages provide default constructors or auto-generate them, but\nalmost universally developers have hooks to create their own constructors when\nnecessary.<\/p>\n<p>Contrast this with Rust or Go, both of which have no explicit concept of a\nuser-authored &quot;constructor&quot;. Instead, both languages have built-in functionality\nto create a new object with some initial data. A &quot;constructor&quot; is simply a\nstandard function that happens to call this built-in. Developers merely wrap\nthis built-in functionality as necessary using the existing features of the\nlanguage.<\/p>\n<h3 id=\"constructors-couple-data-allocation-with-initialization\">Constructors couple data allocation with initialization<\/h3>\n<p>Constructors generally serve the dual purpose of allocating memory for an object\nand initializing it with some input, often with additional validation. However,\n<em>allocating<\/em> an object and <em>initializing<\/em> an object are two very different\noperations with distinct requirements. The former merely needs to know the size\nof the object to allocate, while the latter needs to know the actual inputs and\ntheir semantics to set the object to a valid state.<\/p>\n<p>Contrast this with standard C, where allocation is a completely separate step\nfrom initialization. In C, declaring a <code>struct<\/code> or calling\n<a href=\"https:\/\/en.cppreference.com\/w\/c\/memory\/malloc\" target=\"_blank\"><code>malloc()<\/code><\/a> allocates\nthe memory for it, while developers use the existing features of the language to\nset the object to a valid state. Often a static function will take the required\ninputs, validate them, allocate the <code>struct<\/code>, set the data on it, and return the\nresult in a simplistic form of a constructor.<\/p>\n<h3 id=\"a-superclass-and-a-subclass-are-constructed-at-the-same-time\">A superclass and a subclass are constructed at the same time<\/h3>\n<p>Calling <code>new<\/code> on a subclass which extends a separate superclass will invoke both\nconstructors immediately after each other, with no opportunity to do anything\nelse in between. For example, it is generally impossible to write something\nlike:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">var<\/span> homerPerson <span class=\"token operator\">=<\/span> Person<span class=\"token punctuation\">.<\/span><span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Homer Simpson'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token function\">print<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Successfully invoked Person part of constructor.'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">var<\/span> homerSimpson <span class=\"token operator\">=<\/span> Simpson<span class=\"token punctuation\">.<\/span><span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span>homerPerson<span class=\"token punctuation\">,<\/span> <span class=\"token string\">'Homer'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token function\">print<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Successfully invoked Simpson part of constructor.'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Because the executions of the two constructors are inherently coupled, it\nfundamentally limits the flexibility of constructors as a concept. It also makes\nfactories hard to compose and often have to bend over backwards in order to work\naround this limitation, trying to present a nice API built on awkward\nconstructor behaviors.<\/p>\n<p>Contrast this with JavaScript, which can use its prototypical inheritance to\ndecouple the creation of prototype objects. Note: I am not advocating for\nwriting code this way, just using it to illustrate a different way of thinking.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">const<\/span> homer <span class=\"token operator\">=<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Person<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Homer Simpson'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Successfully invoked Person part of constructor.'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token function\">Simpson<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">apply<\/span><span class=\"token punctuation\">(<\/span>homer<span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">[<\/span> <span class=\"token string\">'Homer'<\/span> <span class=\"token punctuation\">]<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Manually invoke Simpson constructor.<\/span>\nObject<span class=\"token punctuation\">.<\/span><span class=\"token function\">setPrototypeOf<\/span><span class=\"token punctuation\">(<\/span>homer<span class=\"token punctuation\">,<\/span> Simpson<span class=\"token punctuation\">.<\/span>prototype<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Manually assign prototype.<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Successfully invoked Simpson part of constructor.'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Based on these limitations, I believe <strong>the modern concept of constructors is\nfundamentally flawed<\/strong>. I believe we can design languages which provide more\nflexibility and in a much simpler conceptual model than what we currently have\ntoday.<\/p>\n<h2 id=\"a-better-constructor\">A Better Constructor<\/h2>\n<p>So if modern constructors are so bad and have such awkward limitations attached\nto them, then what might be a better system for serving the same purpose? Since\nconstructors are so painful, the simple answer is: &quot;Don&#39;t use them&quot;, or at\nleast: &quot;Use them as little as possible&quot;.<\/p>\n<p>I call this philosophy: <strong>minimal constructors<\/strong>.<\/p>\n<p>This is by no means a new idea, plenty of individuals before me have discussed\nthe challenges with constructors and suggested best practices for working with\nand around them, however I&#39;d like to more directly call out this methodology and\nexplore how it can inform programming language design.<\/p>\n<p>So what is a &quot;minimal constructor&quot;? While they serve many purposes, there is one\nthing constructors can do which (generally) nothing else can: allocate memory.\nAs a result, we can define the term &quot;minimal constructor&quot;:<\/p>\n<blockquote>\n<p>A minimal constructor allocates memory and does nothing more.<\/p>\n<\/blockquote>\n<p>Instead of seeing constructors as a feature of classes to be implemented and\nleveraged, constructors should be thought of as a core primitive of a\nprogramming language, much like built-in data types and operations. Since\nconstructors only allocate memory, it makes sense that developers should not\n<em>implement<\/em> constructors, but merely <em>invoke<\/em> them.<\/p>\n<p>From this core concept, we can build up to a equivalent feature set of modern\nconstructors. For demonstration purposes, imagine a language identical to\nTypeScript but without any concept of constructors. How might we design this\nlanguage to support the same use cases?<\/p>\n<p>By not having constructors this language already saves developers from authoring\nthem and immediately removes 90% of the syntax problems from earlier. If\ndevelopers do not write constructors, then there is no need for a coherent or\nconsistent constructor syntax. However, this means that the compiler must\ngenerate constructors under the hood, so how might a developer use such a\nconstructor? Consider the following TypeScript-like snippet for how this could\nwork:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Person <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Person<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>In this example, there are no user-defined constructors and no <code>constructor<\/code>\nkeyword. <code>new Person()<\/code> works just like default constructors in TypeScript,\nexcept you <em>cannot<\/em> define your own implementation. The <code>new<\/code> keyword is still\nused to invoke this auto-generated constructor, but it is actually closer to a\nC-style <code>malloc()<\/code> call. It really just allocates the memory necessary for\n<code>Person<\/code> and type casts it to the relevant type. We can also restrict the <code>new<\/code>\nkeyword to <strong>only<\/strong> be callable within its own class. Hence the following would\n<strong>not<\/strong> compile:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ COMPILE ERR: `new Person` cannot be used outside the<\/span>\n<span class=\"token comment\">\/\/ `Person` class.<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Person<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>This prevents the <code>new<\/code> keyword from leaking outside the class itself. It also\nmeans we must lean into the factory concept as a <code>static<\/code> method is <strong>required<\/strong>\nto ever instantiate a class. Of course, you probably should <strong>not<\/strong> name the\nfactory <code>new()<\/code> or <code>create()<\/code> or else you will leak that implementation detail\nanyways. I generally recommend <code>of()<\/code> or <code>from()<\/code> to avoid implying that a new\nobject is created, however\n<a href=\"https:\/\/github.com\/microsoft\/TypeScript\/issues\/2536#issuecomment-87194347-permalink:~:text=type-,from,of,-%F0%9F%91%8D\" target=\"_blank\">both of those are reserved keywords in TypeScript<\/a>.\nFor the purposes of readability and simplicity in this blog post I will use\n<code>create()<\/code>, even though you probably should not use that in real use cases.<\/p>\n<p>All the logic that traditionally goes inside constructors can be handled by this\nfactory instead. The constructor is only responsible for allocating memory and\nassigning field members. This nicely separates concerns, as factories are\nresponsible for validating and initializing the object&#39;s data, simply passing\nthe data as inputs to the constructor which get directly assigned to class\nfields.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">readonly<\/span> myFirstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">readonly<\/span> myLastName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>firstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> lastName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Person <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Person<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n      myFirstName<span class=\"token operator\">:<\/span> firstName<span class=\"token punctuation\">,<\/span>\n      myLastName<span class=\"token operator\">:<\/span> lastName<span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">const<\/span> homer <span class=\"token operator\">=<\/span> Person<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Homer'<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">'Simpson'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>homer<span class=\"token punctuation\">.<\/span>myFirstName<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'Homer'<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>homer<span class=\"token punctuation\">.<\/span>myLastName<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'Simpson'<\/span>\n<\/code><\/pre><p>At this point we are somewhat stretching the definition of &quot;minimal&quot;, as we are\nallocating memory, type casting the result, and arguably initializing the class\nall at once. However these simply follow from the conventions of modern\nmemory-managed languages. In such languages, typically all values must have a\ntype and data cannot be uninitialized. These two minor additions allow\nconstructors to fit into the existing semantics of strongly-typed,\nmemory-managed programming languages.<\/p>\n<p>The main takeaway here is that the constructor merely assigns its inputs to\nclass fields, with no application logic applied. This means all initialization\nwork is done in a factory, pulling out these operations to a higher level which\navoids many of the syntactic problems identified earlier. Consider <code>readonly<\/code>\nvariables, which &quot;just work&quot; with <code>if<\/code> statements, <code>for<\/code> loops, or any other\nconstruct:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">const<\/span> homes<span class=\"token operator\">:<\/span> Address<span class=\"token punctuation\">[<\/span><span class=\"token punctuation\">]<\/span> <span class=\"token operator\">=<\/span> <span class=\"token punctuation\">[<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">]<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">readonly<\/span> myHome<span class=\"token operator\">?<\/span><span class=\"token operator\">:<\/span> Address<span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>streetAddress<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Person <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">for<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token keyword\">const<\/span> home <span class=\"token keyword\">of<\/span> homes<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n      <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>home<span class=\"token punctuation\">.<\/span>streetAddress <span class=\"token operator\">===<\/span> streetAddress<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n        <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Person<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> myHome<span class=\"token operator\">:<\/span> home <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n      <span class=\"token punctuation\">}<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Person<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> myHome<span class=\"token operator\">:<\/span> <span class=\"token keyword\">undefined<\/span> <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">const<\/span> homer <span class=\"token operator\">=<\/span> Person<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>homes<span class=\"token punctuation\">,<\/span> <span class=\"token string\">'742 Evergreen Terrace'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>This is much cleaner because <code>readonly<\/code> variables are initialized at the instant\nthe object is constructed. There is no special case where\n<code>this.myHome = ...<\/code> will work. Instead, <code>readonly<\/code> variables can <em>never<\/em> be\nassigned to with no exceptions. No more need for ternary operators or separate\n<code>static<\/code> functions just to work with <code>readonly<\/code>. There is also no need for\ncomplex static analysis in the compiler in order to assert that a <code>readonly<\/code>\nassignment happens exactly once.<\/p>\n<p>At this point, we have a system for creating objects without carrying the burden\nof an overcomplicated constructor mechanism. This is fairly equivalent to what\nGo and Rust have out of the box, and they are great models for this concept.\nHowever, both languages sacrifice one of the more significant features of\nobject-oriented programming: inheritance. Is there any way this kind of\nconstructor system could support inheritance?<\/p>\n<h3 id=\"inheritance\">Inheritance<\/h3>\n<p>The immediate problem with using minimal constructors for\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Inheritance_(object-oriented_programming)\" target=\"_blank\">inheritance<\/a>\nis that invoking a constructor is considered a private implementation detail and\nis <code>private<\/code> to the class being constructed. This is great for creating an\nabstraction but makes inheritance impossible because a subclass does not know\nthe parameters to provide to its superclass&#39; constructor. Factories provide a\npublic API for creating an object, however they do not work well with\ninheritance because they return an already constructed object! What we need is a\nfactory which returns an <em>extendable<\/em> object.<\/p>\n<p>Since factories perform the actual business logic associated with creating an\nobject, factories themselves must be <em>composable<\/em>. In other words, a subclass\nfactory should be able to wrap a superclass factory. Since a superclass factory\ncannot return an instance of the superclass (or else it would already be\nconstructed), it must return some other type. We can call this type <code>ctor&lt;T&gt;<\/code>.<\/p>\n<p><code>ctor&lt;T&gt;<\/code> (short for &quot;constructor of T&quot;) is a self-contained, primitive type\nwhich represents an object that can create an instance of type <code>T<\/code>. This has two\ncore uses: it can defer the construction of an object to a later time, or it can\nbe extended by a subclass.<\/p>\n<p>The first use case is the simplest, as <code>ctor&lt;T&gt;<\/code> has a <code>.construct()<\/code> method to\ncreate an actual instance of <code>T<\/code>.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> myName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token comment\">\/\/ Return a `ctor&lt;Person>`, rather than a `Person` directly.<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">createCtor<\/span><span class=\"token punctuation\">(<\/span>name<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span><\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> myName<span class=\"token operator\">:<\/span> name <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">print<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token keyword\">void<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span><span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>myName<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">const<\/span> homerCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span> <span class=\"token operator\">=<\/span>\n    Person<span class=\"token punctuation\">.<\/span><span class=\"token function\">createCtor<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Homer Simpson'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\nhomerCtor<span class=\"token punctuation\">.<\/span><span class=\"token function\">print<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ COMPILE ERR: print() does not exist on ctor&lt;Person><\/span>\n\n<span class=\"token keyword\">const<\/span> homer<span class=\"token operator\">:<\/span> Person <span class=\"token operator\">=<\/span> homerCtor<span class=\"token punctuation\">.<\/span><span class=\"token function\">construct<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\nhomer<span class=\"token punctuation\">.<\/span><span class=\"token function\">print<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'Homer Simpson'<\/span>\n<\/code><\/pre><p><code>ctor&lt;T&gt;<\/code> is a distinct type, so it does not have access to the methods of <code>T<\/code>.\nSince a <code>T<\/code> has not been constructed yet, it does not make sense to call any\nmethods on it. <code>ctor&lt;T&gt;<\/code> has only one method, <code>.construct()<\/code>, which creates and\nreturns the instance of <code>T<\/code> from its existing data.<\/p>\n<p>While deferred construction is nice, <code>ctor&lt;T&gt;<\/code> has one other key feature: it can\nbe extended. Consider a <code>from<\/code> keyword that can be used in combination with\n<code>new<\/code>. This will allow a subclass to extend a particular instance of a\nsuperclass&#39; <code>ctor&lt;T&gt;<\/code>.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> myLastName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token comment\">\/\/ Return a `ctor&lt;Person>` so it can be extended.<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">createCtor<\/span><span class=\"token punctuation\">(<\/span>lastName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span><\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> myLastName<span class=\"token operator\">:<\/span> lastName <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> myFirstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>firstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Simpson <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">const<\/span> personCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span> <span class=\"token operator\">=<\/span>\n        Person<span class=\"token punctuation\">.<\/span><span class=\"token function\">createCtor<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Simpson'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ Construct a new `Simpson` using the data from `personCtor`.<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Simpson<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> myFirstName<span class=\"token operator\">:<\/span> firstName <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span>\n        from personCtor<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">const<\/span> homer <span class=\"token operator\">=<\/span> Simpson<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Homer'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>homer<span class=\"token punctuation\">.<\/span>myFirstName<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'Homer'<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>homer<span class=\"token punctuation\">.<\/span>myLastName<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'Simpson'<\/span>\n<\/code><\/pre><p>In the above example, the <code>Person<\/code> class is not constructed directly, but rather\nmade into a <code>ctor&lt;Person&gt;<\/code> which simply holds the <code>myLastName<\/code> field as it was\nprovided. <code>Simpson.create()<\/code> wraps the existing <code>Person.createCtor()<\/code>. Once it\nhas the <code>ctor&lt;Person&gt;<\/code> it constructs a <code>Simpson<\/code> based on it using the <code>from<\/code>\nkeyword. <code>from<\/code> in this language simply links a constructor invocation with a\n<code>ctor&lt;SuperClass&gt;<\/code> object, and uses the data that was previously given in the\n<code>new ctor&lt;SuperClass&gt;()<\/code> invocation.<\/p>\n<p>This structure decouples superclass construction from subclass construction.\nConstructor parameters are nicely abstracted behind a factory and do not leak\ninto the subclass. Any number of operations or function calls could be made\nbetween the <code>new<\/code> invocations. The <code>ctor&lt;Person&gt;<\/code> could be passed in and out of\nfunctions, saved to a <code>Map<\/code>, retrieved at later time, and then finally\ninstantiated into a <code>Simpson<\/code>, or maybe even a\n<a href=\"https:\/\/simpsons.fandom.com\/wiki\/Flanders_family\" target=\"_blank\"><code>Flanders<\/code><\/a>.<\/p>\n<p>This also provides simple implementations of class modifiers. Using <code>new<\/code> on an\n<code>abstract<\/code> class can <em>only<\/em> create a <code>ctor&lt;T&gt;<\/code> which does not support a direct\n<code>.construct()<\/code> call. By contrast, using <code>new<\/code> on a closed (<code>final<\/code>) class\ncreates a <code>ctor&lt;T&gt;<\/code> which can <em>never<\/em> be used in a <code>from<\/code> expression. These\ncould be more accurately modeled with <code>abstractCtor&lt;T&gt;<\/code> or <code>closedCtor&lt;T&gt;<\/code>\ntypes, though for simplicity I will just use <code>ctor&lt;T&gt;<\/code> in this post.<\/p>\n<p>This decoupling also removes confusion around <code>this<\/code>. In TypeScript, <code>super()<\/code>\nmust be executed before <code>this<\/code> comes into scope, because the object has not been\ncreated until <code>super()<\/code> is invoked. This awkward foot gun is now impossible\nbecause a reference to <code>this<\/code> refers to the factory context, which is either a\n<code>static<\/code> method, a loose function, or an independent class instance. <code>this<\/code> in a\nfactory will never refer to the constructed object, and it is syntactically\nimpossible to get a reference to the constructed object until after it is fully\nconstructed and in a consistent state.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> myFirstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>firstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Simpson <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ `this` is invalid because we're in a static context.<\/span>\n\n    <span class=\"token keyword\">const<\/span> simpson <span class=\"token operator\">=<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Simpson<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> myFirstName<span class=\"token operator\">:<\/span> firstName <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span>\n        from Person<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'Simpson'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ `this` is still invalid, just use `simpson` to refer<\/span>\n    <span class=\"token comment\">\/\/ to the constructed object!<\/span>\n    <span class=\"token function\">doSomethingInteresting<\/span><span class=\"token punctuation\">(<\/span>simpson<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token keyword\">return<\/span> simpson<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Now at this point we have a system which is roughly equivalent to most\nobject-oriented type systems like Java or C#. We can construct objects and\ninherit from other classes using <code>ctor&lt;T&gt;<\/code>. With a few tweaks in how developers\ndesign their code using <code>ctor&lt;T&gt;<\/code>, it can be used as a mostly drop-in\nreplacement of modern constructors. However, there are a few interesting\n&quot;features&quot; this system can provide which are worth discussing. These certainly\nare not required to gain the benefits of <code>ctor&lt;T&gt;<\/code> and minimal constructors. I\nam also not totally convinced these are good ideas to begin with. However, I do\nbelieve they are at least <em>interesting<\/em>, and it would be a disservice not to\ntalk about them. With that disclaimer out of the way...<\/p>\n<h3 id=\"extending-interfaces\">Extending interfaces<\/h3>\n<p>It was long ago decided in the computer science hive mind that\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Multiple_inheritance\" target=\"_blank\">multiple inheritance<\/a> is a\nbad idea. There are many reasons for this which I will not go into here, however\nmost modern object-oriented languages choose to use a single-inheritance model\nas an alternative. This is much simpler, but provides less flexibility, so\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Interface_(computing)#In_object-oriented_languages:~:text=In%20object%2Doriented%20languages,-%5B\" target=\"_blank\">interfaces<\/a>\nare often touted as the single-inheritance answer to most multiple-inheritance\nuse cases.<\/p>\n<p>However, many developers (myself included) feel that interfaces do not fully\nsatisfy all the use cases for multiple-inheritance. Interfaces provide\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Polymorphism_(computer_science)\" target=\"_blank\">polymorphism<\/a>,\nenabling one class to &quot;masquerade&quot; as another, but interfaces generally do <em>not<\/em>\nenable multiple implementations of an interface to share code, nor do they allow\ndefining fields on an implementation. An interface is an API contract, not a\nfeature or piece of functionality which is shared between many classes. Some\nlanguages fill in this gap via a trait (ex. Rust) or mixin (ex. Dart) system.<\/p>\n<p>However, <code>ctor&lt;T&gt;<\/code> has some interesting implications regarding interfaces. A\ncore property of using <code>ctor&lt;T&gt;<\/code>, is that a subclass is no longer responsible\nfor invoking its superclass&#39; constructor via <code>super()<\/code>. The <code>ctor&lt;T&gt;<\/code> object is\nresponsible for holding class fields and setting them on the final constructed\nobject. One interesting side effect of not relying on a subclass to invoke its\nsuperclass&#39; constructor, is that the subclass does <em>not<\/em> require a direct\nreference to its superclass. This has some unique implications regarding\ninterfaces, most notably that <strong>extending a class only requires knowledge of a\nits supported interface, not its actual implementation.<\/strong><\/p>\n<p>Take for example, the following TypeScript-like code modeling Simpsons who also\nhappen to be students:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">interface<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token function\">think<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ Make an implementation of `Person`.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Student<\/span> <span class=\"token keyword\">implements<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token comment\">\/\/ Satisfies the `Person` interface.<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">think<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token string\">'What time is recess?'<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Student<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">ctor<span class=\"token operator\">&lt;<\/span>Student<span class=\"token operator\">><\/span><\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ `Simpson` \"extends\" the `Person` interface. This can be<\/span>\n<span class=\"token comment\">\/\/ thought of as `Simpson` extending an *unknown<\/span>\n<span class=\"token comment\">\/\/ implementation* of `Person`. `Simpson` has no knowledge<\/span>\n<span class=\"token comment\">\/\/ of what superclass it actually has, it only knows that<\/span>\n<span class=\"token comment\">\/\/ the superclass implements `Person`.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> myCatchphrase<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">say<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ `Simpson` can invoke `think()` because it knows its<\/span>\n    <span class=\"token comment\">\/\/ superclass implements it. Simpsons are known for<\/span>\n    <span class=\"token comment\">\/\/ blurting out whatever they are thinking.<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">think<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">+<\/span> <span class=\"token string\">' '<\/span> <span class=\"token operator\">+<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>myCatchphrase<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token comment\">\/\/ Constructs off some `ctor&lt;Person>`. Any implementation<\/span>\n  <span class=\"token comment\">\/\/ of `Person` can be provided here and it will be<\/span>\n  <span class=\"token comment\">\/\/ extended to make a `Simpson`.<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token generic-function\"><span class=\"token function\">create<\/span><span class=\"token generic class-name\"><span class=\"token operator\">&lt;<\/span>TParent <span class=\"token keyword\">extends<\/span> Person<span class=\"token operator\">><\/span><\/span><\/span><span class=\"token punctuation\">(<\/span>\n      parentCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>TParent<span class=\"token operator\">><\/span><span class=\"token punctuation\">,<\/span> catchphrase<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Simpson <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Simpson<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n      myCatchphrase<span class=\"token operator\">:<\/span> catchphrase<span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span> from parentCtor<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ `Simpson` can now extend from `Student`, without having<\/span>\n<span class=\"token comment\">\/\/ knowledge of it. Bart is one particular Simpson who also<\/span>\n<span class=\"token comment\">\/\/ happens to be a student.<\/span>\n<span class=\"token keyword\">const<\/span> studentCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Student<span class=\"token operator\">><\/span> <span class=\"token operator\">=<\/span> Student<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">const<\/span> bart<span class=\"token operator\">:<\/span> Simpson <span class=\"token operator\">=<\/span>\n    Simpson<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>studentCtor<span class=\"token punctuation\">,<\/span> <span class=\"token string\">'Eat my shorts!'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ `Student` satisfies the `Person` interface.<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>bart<span class=\"token punctuation\">.<\/span><span class=\"token function\">think<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'What time is recess?'<\/span>\n\n<span class=\"token comment\">\/\/ `Simpson` can also call its superclass.<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>bart<span class=\"token punctuation\">.<\/span><span class=\"token function\">say<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'What time is recess? Eat my shorts!'<\/span>\n<\/code><\/pre><p>The idea of &quot;extending an unknown implementation of a known interface&quot; provides\nmuch more power and flexibility to the traditional concept of interfaces. It\nstill provides polymorphism, as <code>Student<\/code> and <code>Simpson<\/code> can both be cast to\n<code>Person<\/code>. It also allows <code>Simpson<\/code> to rely on its superclass to provide the\n<code>Person<\/code> interface, meaning the implementation of <code>think()<\/code> can be shared across\nmultiple subclasses who extend the <code>Person<\/code> interface but may not be Simpsons,\nlike <a href=\"https:\/\/simpsons.fandom.com\/wiki\/Milhouse_Van_Houten\" target=\"_blank\">Milhouse<\/a> or\n<a href=\"https:\/\/simpsons.fandom.com\/wiki\/Ralph_Wiggum\" target=\"_blank\">Ralph<\/a>. Both <code>Simpson<\/code> and\n<code>Student<\/code> also own their own factories, meaning they can both declare their own\nfields and encapsulate their own relevant state. This is far more powerful than\na traditional single-inheritance interface.<\/p>\n<h3 id=\"dynamic-inheritance-hierarchy\">Dynamic inheritance hierarchy<\/h3>\n<p>There is an interesting consequence of allowing a class to extend an unknown\nimplementation of an interface: a class can actually extend from a set of\nmultiple superclasses, chosen dynamically at runtime. This has a few,\nfar-reaching effects.<\/p>\n<p>On the one hand, it means that a class can dynamically choose its superclass at\nruntime, via its own condition or having that superclass provided as an input to\na factory. Take for example a simple <code>Student<\/code> use case. Here, we want two\nimplementations, one for good students and another for bad students. Then, we\nwant to have a <code>FourthGrader<\/code> class that applies specifically to 4th graders\nlike Bart. How can we design the <code>FourthGrader<\/code> class to reuse our good\/bad\ndistinction?<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">interface<\/span> <span class=\"token class-name\">Student<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ Two implementations of `Student`, one with good grades<\/span>\n<span class=\"token comment\">\/\/ who studies hard, and another for Bart.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">GoodStudent<\/span> <span class=\"token keyword\">implements<\/span> <span class=\"token class-name\">Student<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">BadStudent<\/span> <span class=\"token keyword\">implements<\/span> <span class=\"token class-name\">Student<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ A simple function to choose the ideal implementation of a<\/span>\n<span class=\"token comment\">\/\/ `Student` based on their grades.<\/span>\n<span class=\"token keyword\">function<\/span> <span class=\"token function\">createStudent<\/span><span class=\"token punctuation\">(<\/span>grade<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Student<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">if<\/span> <span class=\"token punctuation\">(<\/span>grade <span class=\"token operator\">===<\/span> <span class=\"token string\">'A'<\/span> <span class=\"token operator\">||<\/span> grade <span class=\"token operator\">===<\/span> <span class=\"token string\">'B'<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> GoodStudent<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">else<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> BadStudent<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ Extend any implementation of `Student`.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">FourthGrader<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Student<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token comment\">\/\/ Springfield Elementary seems to have only one 4th grade teacher.<\/span>\n  <span class=\"token keyword\">private<\/span> teacher<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token operator\">=<\/span> <span class=\"token string\">'Krabappel'<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>grade<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> FourthGrader <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Dynamically choose the appropriate `Student`<\/span>\n    <span class=\"token comment\">\/\/ implementation as a superclass.<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">FourthGrader<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> from <span class=\"token function\">createStudent<\/span><span class=\"token punctuation\">(<\/span>grade<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">const<\/span> bart <span class=\"token operator\">=<\/span> FourthGrader<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'D'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ is `BadStudent`<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>bart <span class=\"token keyword\">instanceof<\/span> <span class=\"token class-name\">BadStudent<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ `true`<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>bart <span class=\"token keyword\">instanceof<\/span> <span class=\"token class-name\">GoodStudent<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ `false`<\/span>\n\n<span class=\"token keyword\">const<\/span> martin <span class=\"token operator\">=<\/span> FourthGrader<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token string\">'A'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ is `GoodStudent`<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>bart <span class=\"token keyword\">instanceof<\/span> <span class=\"token class-name\">BadStudent<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ `false`<\/span>\n<span class=\"token builtin\">console<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">log<\/span><span class=\"token punctuation\">(<\/span>bart <span class=\"token keyword\">instanceof<\/span> <span class=\"token class-name\">GoodStudent<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ `true`<\/span>\n<\/code><\/pre><p>Here, <code>FourthGrader<\/code> is dynamically choosing at runtime whether to extend a\n<code>GoodStudent<\/code> or a <code>BadStudent<\/code>, reusing any functionality they may provide.\nSince <code>FourthGrader<\/code> extends an unknown implementation of <code>Student<\/code>, it is not\nintrinsically bound to any particular superclass. This reduces overall coupling\nbetween the classes and nicely reuses the existing code. Lisa could be an\ninstance of a <code>SecondGrader<\/code> class which shares functionality with <code>GoodStudent<\/code>\nand <code>BadStudent<\/code>.<\/p>\n<p>This is a really useful feature, as this same design would be quite difficult to\nachieve with traditional class hierarchies. You would either need a\n<code>GoodFourthGrader<\/code> and a <code>BadFourthGrader<\/code> as distinct subclasses with\nduplicated functionality or you would need to refactor the whole thing to use a\nmixin or trait system, if you are lucky enough to use a language which supports\nthem.<\/p>\n<p>On the other hand, this means that class hierarchies are not statically known at\ncompile-time. Any open implementation of a particular interface could\npotentially be used as a superclass which extends that interface. While\neverything is still reasonably typed and can be checked at compile-time, the\nprecise class hierarchy may vary at runtime, and could even differ between\ndifferent instances of the same class. A <code>FourthGrader<\/code> with an A grade will\nextend <code>GoodStudent<\/code>, while a different <code>FourthGrader<\/code> with a D grade will\nextend <code>BadStudent<\/code> and could exist in the same program and even interact with\neach other. This makes reasoning about <code>FourthGrader<\/code> a bit harder, as any\n<code>super.study()<\/code> call could refer to any implementation of <code>Student<\/code> rather than\na fixed superclass.<\/p>\n<h3 id=\"mixins\">Mixins<\/h3>\n<p>The idea of &quot;extending an unknown implementation&quot; is basically the definition of\na <a href=\"https:\/\/en.wikipedia.org\/wiki\/Mixin\" target=\"_blank\">mixin<\/a>. Languages vary widely in their\nsupport of a mixin mechanism, and those that do often have their own problems\nwith constructors. Take a TypeScript example, where mixins are often implemented\nas a function which converts a class definition into an anonymous class with the\nmixin behavior included.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">type<\/span> <span class=\"token class-name\">Constructor<\/span> <span class=\"token operator\">=<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token operator\">...<\/span>args<span class=\"token operator\">:<\/span> <span class=\"token builtin\">any<\/span><span class=\"token punctuation\">[<\/span><span class=\"token punctuation\">]<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span><span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">function<\/span> <span class=\"token generic-function\"><span class=\"token function\">Simpson<\/span><span class=\"token generic class-name\"><span class=\"token operator\">&lt;<\/span>TBase <span class=\"token keyword\">extends<\/span> Constructor<span class=\"token operator\">><\/span><\/span><\/span><span class=\"token punctuation\">(<\/span>Base<span class=\"token operator\">:<\/span> TBase<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token comment\">\/\/ Return a new class which extends the one provided.<\/span>\n  <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">class<\/span> <span class=\"token class-name\"><span class=\"token keyword\">extends<\/span><\/span> Base <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Add mixin functionality.<\/span>\n    <span class=\"token keyword\">public<\/span> <span class=\"token function\">say<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n      <span class=\"token keyword\">return<\/span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">D'oh!<\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n  <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>While this works great for simple cases, it starts to break down with\nconstructors. Consider changing this so the <code>D&#39;oh!<\/code> string literal was provided\nas a constructor parameter.<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">type<\/span> <span class=\"token class-name\">Constructor<\/span> <span class=\"token operator\">=<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token punctuation\">(<\/span><span class=\"token operator\">...<\/span>args<span class=\"token operator\">:<\/span> <span class=\"token builtin\">any<\/span><span class=\"token punctuation\">[<\/span><span class=\"token punctuation\">]<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token operator\">=><\/span> <span class=\"token punctuation\">{<\/span><span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token keyword\">function<\/span> <span class=\"token generic-function\"><span class=\"token function\">Simpson<\/span><span class=\"token generic class-name\"><span class=\"token operator\">&lt;<\/span>TBase <span class=\"token keyword\">extends<\/span> Constructor<span class=\"token operator\">><\/span><\/span><\/span><span class=\"token punctuation\">(<\/span>Base<span class=\"token operator\">:<\/span> TBase<span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token comment\">\/\/ Return a new class which extends the one provided.<\/span>\n  <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">class<\/span> <span class=\"token class-name\"><span class=\"token keyword\">extends<\/span><\/span> Base <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">public<\/span> myCatchphrase<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n    <span class=\"token comment\">\/\/ COMPILE ERR: A mixin class must have a constructor<\/span>\n    <span class=\"token comment\">\/\/ with a single rest parameter of type 'any[]'<\/span>\n    <span class=\"token keyword\">public<\/span> <span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span>catchphrase<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token operator\">...<\/span>args<span class=\"token operator\">:<\/span> <span class=\"token builtin\">any<\/span><span class=\"token punctuation\">[<\/span><span class=\"token punctuation\">]<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n      <span class=\"token keyword\">super<\/span><span class=\"token punctuation\">(<\/span><span class=\"token operator\">...<\/span>args<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n      <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>myCatchphrase <span class=\"token operator\">=<\/span> catchphrase<span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n\n    <span class=\"token comment\">\/\/ Add mixin functionality.<\/span>\n    <span class=\"token keyword\">public<\/span> <span class=\"token function\">say<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n      <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>myCatchphrase<span class=\"token punctuation\">;<\/span>\n    <span class=\"token punctuation\">}<\/span>\n  <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">;<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>We run into a problem with constructor arguments. This is because a mixin, by\ndefinition, does not have knowledge of its superclass and has no way of knowing\nwhat to provide. TypeScript actually requires that mixins like this declare\ntheir constructors with <code>...args: any[]<\/code> specifically for this reason (though\nIMHO this is overly strict and I do not understand why it is necessary). Other\nlimitations of constructors from the <code>super()<\/code> syntax further complicate this to\nmake it very difficult to extract the first argument as the mixin string and\npass through the rest to the superclass. The end result here, is that it is\nnear-impossible to pass in a value to a mixin through its constructor in\nTypeScript.<\/p>\n<p>With <code>ctor&lt;T&gt;<\/code>, a mixin pattern works just like extending an interface which we\ncan use to model the\n<a href=\"https:\/\/simpsons.fandom.com\/wiki\/I,_(Annoyed_Grunt)-Bot\" target=\"_blank\">many cats of the Simpsons<\/a>:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/\/ A mixin simply extends an unknown type parameter. We do<\/span>\n<span class=\"token comment\">\/\/ not need to know what `TParent` is at compile-time,<\/span>\n<span class=\"token comment\">\/\/ because we do not need a value reference to its<\/span>\n<span class=\"token comment\">\/\/ implementation. This is only used to type-check the<\/span>\n<span class=\"token comment\">\/\/ `from` clause.<\/span>\n<span class=\"token comment\">\/\/<\/span>\n<span class=\"token comment\">\/\/ Simpsons say their catchphrase.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<span class=\"token operator\">&lt;<\/span>TParent<span class=\"token operator\">><\/span><\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">TParent<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">readonly<\/span> myCatchphrase<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">say<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>myCatchphrase<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token comment\">\/\/ Construct from any given `ctor&lt;T>`. Must use a<\/span>\n  <span class=\"token comment\">\/\/ function-specific generic because as a static function,<\/span>\n  <span class=\"token comment\">\/\/ `TParent` is not in scope or known at this time.<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token generic-function\"><span class=\"token function\">create<\/span><span class=\"token generic class-name\"><span class=\"token operator\">&lt;<\/span>TSuper<span class=\"token operator\">><\/span><\/span><\/span><span class=\"token punctuation\">(<\/span>parentCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>TSuper<span class=\"token operator\">><\/span><span class=\"token punctuation\">,<\/span> catchphrase<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span>\n      ctor<span class=\"token operator\">&lt;<\/span>Simpson<span class=\"token operator\">&lt;<\/span>TSuper<span class=\"token operator\">>><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">ctor<span class=\"token operator\">&lt;<\/span>Simpson<span class=\"token operator\">&lt;<\/span>TSuper<span class=\"token operator\">>><\/span><\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n      myCatchphrase<span class=\"token operator\">:<\/span> catchphrase<span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span> from parentCtor<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ Define a simple parent class, with no knowledge of<\/span>\n<span class=\"token comment\">\/\/ `Simpson`. Cats simply have a color provided as a factory<\/span>\n<span class=\"token comment\">\/\/ parameter.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Cat<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> myColor<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>color<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Cat<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">ctor<span class=\"token operator\">&lt;<\/span>Cat<span class=\"token operator\">><\/span><\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> myColor<span class=\"token operator\">:<\/span> color <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ `Snowball` extends `Cat` mixed with `Simpson`.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Snowball<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Simpson<span class=\"token operator\">&lt;<\/span>Cat<span class=\"token operator\">><\/span><\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> myIteration<span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">act<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ `Snowball` can reference both `Simpson` and `Cat` members.<\/span>\n    <span class=\"token comment\">\/\/ It has color and catchphrase functionality from each.<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token string\">'The '<\/span> <span class=\"token operator\">+<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>myColor <span class=\"token operator\">+<\/span> <span class=\"token string\">' Snowball '<\/span>\n        <span class=\"token operator\">+<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>myIteration <span class=\"token operator\">+<\/span> <span class=\"token string\">' says '<\/span> <span class=\"token operator\">+<\/span> <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">say<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>iteration<span class=\"token operator\">:<\/span> <span class=\"token builtin\">number<\/span><span class=\"token punctuation\">,<\/span> color<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Cat <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Call `Simpson` factory with a `ctor&lt;Cat>`.<\/span>\n    <span class=\"token keyword\">const<\/span> catCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Cat<span class=\"token operator\">><\/span> <span class=\"token operator\">=<\/span> Cat<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>color<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">const<\/span> simpsonCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Simpson<span class=\"token operator\">&lt;<\/span>Cat<span class=\"token operator\">>><\/span> <span class=\"token operator\">=<\/span>\n        Simpson<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>catCtor<span class=\"token punctuation\">,<\/span> <span class=\"token string\">'Meow...'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">Snowball<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span>\n      myIteration<span class=\"token operator\">:<\/span> iteration<span class=\"token punctuation\">,<\/span>\n    <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span> from catCtor<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\nSnowball<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token number\">1<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">'white'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">act<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'The white Snowball 1 says Meow...'<\/span>\nSnowball<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token number\">2<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">'black'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">act<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'The black Snowball 2 says Meow...'<\/span>\nSnowball<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token number\">3<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">'brown'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">act<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'The brown Snowball 3 says Meow...'<\/span>\nSnowball<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token number\">4<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">'gray'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">act<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>  <span class=\"token comment\">\/\/ 'The gray Snowball 4 says Meow...'<\/span>\nSnowball<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span><span class=\"token number\">5<\/span><span class=\"token punctuation\">,<\/span> <span class=\"token string\">'black'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">act<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ 'The black Snowball 5 says Meow...'<\/span>\n<\/code><\/pre><p>With <code>ctor&lt;T&gt;<\/code>, we are able to define a mixin as a class that will extend any\ngiven superclass. This is done by simply allowing a class to extend its own type\nparameter, since all &quot;extending&quot; does is simply type check the <code>from<\/code>\nclause of a <code>new<\/code> expression.<\/p>\n<p>Using mixins with <code>ctor&lt;T&gt;<\/code> composes factories smoothly and allows each mixin to\nown its own constructor parameters. You can even introduce type constraints on\nthe classes that can be used with a given mixin simply by adding those\nconstraints to the generic:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/\/ Standard base class representing a person.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ `Simpson` is a mixin that extends a class of any type.<\/span>\n<span class=\"token comment\">\/\/ Makes no assumptions about what that superclass is.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<span class=\"token operator\">&lt;<\/span><span class=\"token constant\">T<\/span><span class=\"token operator\">><\/span><\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\"><span class=\"token constant\">T<\/span><\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ All students are people, so we constrain `Student` to<\/span>\n<span class=\"token comment\">\/\/ extend only a `Person`.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Student<span class=\"token operator\">&lt;<\/span><span class=\"token constant\">T<\/span> <span class=\"token keyword\">extends<\/span> Person<span class=\"token operator\">><\/span><\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\"><span class=\"token constant\">T<\/span><\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ `Simpson&lt;Person>` satisfies the `Student` type constraint.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">SimpsonChild<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Student<span class=\"token operator\">&lt;<\/span>Simpson<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">>><\/span><\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Cat<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ COMPILE ERR: Type parameter of `Student` must extend<\/span>\n<span class=\"token comment\">\/\/ `Person`.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">SimpsonPet<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Student<span class=\"token operator\">&lt;<\/span>Simpson<span class=\"token operator\">&lt;<\/span>Cat<span class=\"token operator\">>><\/span><\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Note that not much needs to change to support mixins, as they mostly &quot;just\nwork&quot;\u1d57\u1d50. This shows the power and flexibility of <code>ctor&lt;T&gt;<\/code> which comes from\ndecoupling a superclass from its subclasses, which is all enabled with the use\nof minimal constructors.<\/p>\n<h2 id=\"experimental-implementation\">Experimental implementation<\/h2>\n<p>While authoring this post, I wanted to actually play around with these ideas and\nmake sure they worked as well as I hoped. A proper implementation would require\na custom compiler, or at least a compiler plugin, however a library could be\n&quot;good enough&quot; for small experiments. As a result, I published\n<a href=\"https:\/\/github.com\/dgp1130\/ctor-exp\" target=\"_blank\"><code>ctor-exp<\/code><\/a>, a simple\nTypeScript library which implements many of the ideas here.<\/p>\n<p>TypeScript has an <del>abusable<\/del> powerful enough type system to emulate a lot of\nthe core concepts without strictly requiring a compiler plugin. This library is\nable to implement most of the critical features, just with less-than-ideal\nsyntax and only a 3-star safety rating. The repository explains how to use it in\ndetail, but here is a rough translation with the idealized system described\nabove:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">import<\/span> <span class=\"token punctuation\">{<\/span> ctor<span class=\"token punctuation\">,<\/span> from<span class=\"token punctuation\">,<\/span> Implementation <span class=\"token punctuation\">}<\/span> <span class=\"token keyword\">from<\/span> <span class=\"token string\">'ctor-exp'<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">readonly<\/span> myName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token comment\">\/\/ Constructors must be hand-written in this format.<\/span>\n  <span class=\"token comment\">\/\/ Must be `public`, but should not be called outside the<\/span>\n  <span class=\"token comment\">\/\/ class.<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> myName <span class=\"token punctuation\">}<\/span><span class=\"token operator\">:<\/span> <span class=\"token punctuation\">{<\/span> myName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>myName <span class=\"token operator\">=<\/span> myName<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>name<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Person <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Equivalent to: `new Person({ myName: name })`.<\/span>\n    <span class=\"token keyword\">return<\/span> ctor<span class=\"token punctuation\">.<\/span><span class=\"token function\">new<\/span><span class=\"token punctuation\">(<\/span>Person<span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">{<\/span> myName<span class=\"token operator\">:<\/span> name <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">.<\/span><span class=\"token function\">construct<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">extend<\/span><span class=\"token punctuation\">(<\/span>name<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Equivalent to: `new ctor&lt;Person>({ myName: name })`.<\/span>\n    <span class=\"token keyword\">return<\/span> ctor<span class=\"token punctuation\">.<\/span><span class=\"token function\">new<\/span><span class=\"token punctuation\">(<\/span>Person<span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">{<\/span> myName<span class=\"token operator\">:<\/span> name <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token comment\">\/\/ Extend `Implementation&lt;SuperClass>()` rather than<\/span>\n<span class=\"token comment\">\/\/ `SuperClass` directly.<\/span>\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Implementation<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span><\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">private<\/span> <span class=\"token keyword\">readonly<\/span> myFirstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">;<\/span>\n\n  <span class=\"token comment\">\/\/ Subclass constructors are the same, but with an empty<\/span>\n  <span class=\"token comment\">\/\/ `super()` call.<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">constructor<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">{<\/span> myFirstName <span class=\"token punctuation\">}<\/span><span class=\"token operator\">:<\/span> <span class=\"token punctuation\">{<\/span> myFirstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">super<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n    <span class=\"token keyword\">this<\/span><span class=\"token punctuation\">.<\/span>myFirstName <span class=\"token operator\">=<\/span> myFirstName<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>firstName<span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> Simpson <span class=\"token punctuation\">{<\/span>\n    <span class=\"token comment\">\/\/ Equivalent to:<\/span>\n    <span class=\"token comment\">\/\/ new Simpson({ myFirstName: firstName })<\/span>\n    <span class=\"token comment\">\/\/     from Person.extend(firstName + ' Simpson')<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token function\">from<\/span><span class=\"token punctuation\">(<\/span>Person<span class=\"token punctuation\">.<\/span><span class=\"token function\">extend<\/span><span class=\"token punctuation\">(<\/span>firstName <span class=\"token operator\">+<\/span> <span class=\"token string\">' Simpson'<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">)<\/span>\n        <span class=\"token punctuation\">.<\/span><span class=\"token function\">new<\/span><span class=\"token punctuation\">(<\/span>Simpson<span class=\"token punctuation\">,<\/span> <span class=\"token punctuation\">{<\/span> myFirstName<span class=\"token operator\">:<\/span> firstName <span class=\"token punctuation\">}<\/span><span class=\"token punctuation\">)<\/span>\n        <span class=\"token punctuation\">.<\/span><span class=\"token function\">construct<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Hopefully this provides a close-enough approximation to a real implementation\nfor devs to experiment with. There are also a number of\n<a href=\"https:\/\/github.com\/dgp1130\/ctor-exp#examples\" target=\"_blank\">examples of real world use cases<\/a>\nto compare a <code>ctor&lt;T&gt;<\/code> approach with traditional constructors, including some of\nthe more out-there features like dynamically choosing a superclass at runtime.\nCheck it out and let me know how well some real world examples hold up!<\/p>\n<h2 id=\"what-about-builders\">What about builders?<\/h2>\n<p>An astute reader may pose the question: &quot;Isn&#39;t this just the\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Builder_pattern\" target=\"_blank\">builder pattern<\/a>? <code>ctor&lt;T&gt;<\/code> is\njust a <code>Builder&lt;T&gt;<\/code> type.&quot; To which my response is: <em>Why yes it is Mr. and\/or\nMs. Smarty Pants, way to steal my thunder here.<\/em> More seriously, while a\n<code>ctor&lt;T&gt;<\/code> type (or something very similar to it) can be implemented with a\ntraditional builder class, there are a few core differences with builders:<\/p>\n<ul>\n<li><code>ctor&lt;T&gt;<\/code> and &quot;minimal constructors&quot; is more about re-conceptualizing the\n<em>concept<\/em> of a constructor, forcing developers to think more in terms of\nfactories. It decouples memory allocation (constructors) from initialization\nand validation (factories). While this can be done with builders, it is not\ninherent in the builder design pattern.<\/li>\n<li>Composing builders throughout an inheritance hierarchy can be quite complex\n(though not impossible) and requires coordination between different classes in\nthe hierarchy as well as adherence to custom API contracts. <code>ctor&lt;T&gt;<\/code> provides\na much cleaner and more uniform interface to this concept.<\/li>\n<li>With <code>ctor&lt;T&gt;<\/code>, the compiler <strong>requires<\/strong> developers to always use this\npattern, preventing devs from cornering themselves into a bad design which is\ndifficult to get out of without breaking API contracts.<\/li>\n<li>The compiler automatically generates all the required builder code, as this is\nfar too much boilerplate to be practical in most languages without direct\ncompiler support.<\/li>\n<\/ul>\n<p>So while the <code>ctor&lt;T&gt;<\/code> implementation of minimal constructors is <em>technically<\/em> a\nspecial case of the builder design pattern, &quot;minimal constructors&quot; refers to a\nmore general paradigm of thinking and interacting with constructors which is\nmuch more clearly expressed via <code>ctor&lt;T&gt;<\/code>.<\/p>\n<h2 id=\"drawbacks\">Drawbacks<\/h2>\n<p>While I definitely see this new concept of constructors as an improvement over\nexisting methodologies, there are a few caveats to consider. Not all of these\napply to the minimal implementation of <code>ctor&lt;T&gt;<\/code> and inheritance, so the extent\nto which a language uses the concepts described in this post will vary the kind\nand extent of these drawbacks it encounters.<\/p>\n<h3 id=\"extending-a-sibling\">Extending a sibling<\/h3>\n<p>Consider the following class hierarchy:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">interface<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>parentCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Simpson<span class=\"token operator\">><\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">ctor<span class=\"token operator\">&lt;<\/span>Simpson<span class=\"token operator\">><\/span><\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> from parentCtor<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">VanHouten<\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token keyword\">static<\/span> <span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>parentCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> VanHouten <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token keyword\">new<\/span> <span class=\"token class-name\">VanHouten<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span> from parentCtor<span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n<\/code><\/pre><p>Because <code>Person<\/code> is an interface, both <code>Simpson<\/code> and <code>VanHouten<\/code> are capable of\nextending any class which satisfies the <code>Person<\/code> interface. While this provides\na lot of flexibility, it also means the following is possible:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token comment\">\/\/ `Simpson` extends some `Person` implementation.<\/span>\n<span class=\"token keyword\">const<\/span> personCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">><\/span> <span class=\"token operator\">=<\/span> <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token keyword\">const<\/span> simpsonCtor<span class=\"token operator\">:<\/span> ctor<span class=\"token operator\">&lt;<\/span>Simpson<span class=\"token operator\">><\/span> <span class=\"token operator\">=<\/span> Simpson<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>personCtor<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n\n<span class=\"token comment\">\/\/ `VanHouten` extends `Simpson`, which satisfies the<\/span>\n<span class=\"token comment\">\/\/ `Person` interface?!?!<\/span>\n<span class=\"token keyword\">const<\/span> zia<span class=\"token operator\">:<\/span> VanHouten <span class=\"token operator\">=<\/span> VanHouten<span class=\"token punctuation\">.<\/span><span class=\"token function\">create<\/span><span class=\"token punctuation\">(<\/span>simpsonCtor<span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span>\n<\/code><\/pre><p>Since <code>Simpson<\/code> satisfies the <code>Person<\/code> interface and <code>VanHouten<\/code> only needs a\n<code>ctor&lt;Person&gt;<\/code>, this is satisfied by <code>ctor&lt;Simpson&gt;<\/code> and will compile\nsuccessfully. We have now created a <code>VanHouten<\/code> which extends a <code>Simpson<\/code> in a\nway the programmer definitely did not intend when they first authored those\nclasses. This was clearly intended to be a sibling relationship but has turned\ninto a parent-child relationship, resulting in\n<a href=\"https:\/\/simpsons.fandom.com\/wiki\/Zia_Simpson-Van_Houten\" target=\"_blank\">Zia Simpson-Van Houten<\/a>\nwhich is non-canon and definitely should be disallowed by the compiler.<\/p>\n<p>While this does speak to the flexibility and power of the concept of extending\ninterfaces, it also shows a way it can be misused. Ultimately there is really no\nway for the language to know whether two classes are intended to be siblings or\nnot. If <code>Simpson<\/code> were declared as closed\/<code>final<\/code>, then this would be\ncompile-time error. However if there are other, legitimate uses of extending\n<code>Simpson<\/code>, then there is no way to prevent <code>VanHouten<\/code> from incorrectly\nextending it. You could even make a <code>Simpson<\/code> extend <em>another<\/em> <code>Simpson<\/code> and\ndestroy the space-time continuum!<\/p>\n<p>This is a significant foot-gun which developers would need to be aware of and\nwatch out for. It also highlights the advantage of simply extending a known\nsuperclass, rather than an unknown implementation of a known interface. For this\nreason, it is likely better to extend a known superclass whenever the features\nof extending an interface are not required. This would restrict the class\nhierarchy and reduce the possibility of bugs. Devs should only extend an\ninterface when there is an actual design need and benefit to doing so.<\/p>\n<h3 id=\"construction-time-execution\">Construction-time execution<\/h3>\n<p>One possible concern with <code>ctor&lt;T&gt;<\/code> that superclasses do not have any hook which\nexecutes at construction-time (when the final concrete subclass invokes <code>new<\/code>).\nThis means that superclasses cannot perform any initialization or validation at\nconstruction-time, only at factory-invocation-time.<\/p>\n<p>This has one positive side effect in that it is impossible for a superclass to\ncall an abstract method implemented by a subclass during construction.\n<a href=\"https:\/\/tinyurl.com\/mtn8rddh\" target=\"_blank\">This is possible in TypeScript and Java<\/a>, but\nheavily discouraged because it means the subclass&#39; implementation of that\nabstract method will be invoked before its constructor has a chance to\ninitialize it. That benefit makes me believe that the lack of construction-time\nexecution in a superclass is actually a feature rather than a bug.<\/p>\n<p>However, if the lack of construction-time computations really became an issue,\nsome kind of <code>onConstruct()<\/code> method could be called which would enable the class\nto do whatever it needed to. I would try to avoid this if possible as I think\nmany classes would be better designed without this feature, but it may be\nimpractical to avoid in some use cases.<\/p>\n<h3 id=\"memory-fragmentation\">Memory fragmentation<\/h3>\n<p>In many natively compiled languages like C++, member fields of a subclass are\ncollocated alongside member fields of a superclass, with a reference to the\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Virtual_method_table\" target=\"_blank\">virtual method table (vtable)<\/a>.\nIn such languages, <code>new<\/code> can only be invoked on the concrete subclass being\nconstructed, and because the inheritance hierarchy is statically known, the\ntotal size of the subclass is also known and the entire object can be allocated\nall at once.<\/p>\n<p>A <code>ctor&lt;T&gt;<\/code>-based system would likely be impossible to implement this way due to\nthe lack of a direct reference to a known, constant superclass. The total size\nof a given subclass simply is not known at compile-time because we do not know\nthe specific superclass implementation which will be used. Even for uses that\nactually do extend a known, constant superclass, it would not be enough. A\nparticular <code>new ctor&lt;T&gt;()<\/code> call for the superclass could eventually be\ninstantiated into any one of many different subclasses of <code>T<\/code>, with no way of\nknowing which it will become, or how much memory to allocate. Even the vtable\ncould encounter implementation hurdles due to the dynamic nature of the\ninheritance hierarchy.<\/p>\n<p>There are certainly ways around this issue. The compiler could separate the\nsuperclass&#39; memory from the subclass, simply leaving pointers to get from one to\nthe other, this means the size of the entire hierarchy is not needed, but would\nhave negative runtime impact due to additional pointer indirections and may\nrequire runtime type reflection to know when an indirection is needed.\nAlternatively, the compiler could use this indirection strategy for <code>ctor&lt;T&gt;<\/code>\ntypes and then copy them into a single contiguous space when <code>.construct()<\/code> is\ncalled. This means accessing fields of a parent class do not require pointer\nindirection or runtime type reflection, but additional copying would be\nnecessary in the implementation of <code>.construct()<\/code>. There are also other means of\nmethod dispatch than vtables, though they come with their own costs.<\/p>\n<p>The real point here is that using <code>ctor&lt;T&gt;<\/code> as a drop-in replacement for a\nnatively-compiled language like C++ would probably encounter a lot of\nimplementation challenges. An interpreted language would likely have a much\neasier time implementing this model.<\/p>\n<h3 id=\"symbol-conflicts\">Symbol conflicts<\/h3>\n<p>Mixing two unrelated classes together in an inheritance hierarchy also comes\nwith the possibility of symbol conflicts. Take the following example:<\/p>\n<pre><code class=\"language-typescript\"><span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Person<\/span> <span class=\"token punctuation\">{<\/span> <span class=\"token comment\">\/* ... *\/<\/span> <span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Simpson<span class=\"token operator\">&lt;<\/span><span class=\"token constant\">T<\/span><span class=\"token operator\">><\/span><\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\"><span class=\"token constant\">T<\/span><\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">say<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`<\/span><span class=\"token string\">D'oh!<\/span><span class=\"token template-punctuation string\">`<\/span><\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">class<\/span> <span class=\"token class-name\">Student<span class=\"token operator\">&lt;<\/span><span class=\"token constant\">T<\/span><span class=\"token operator\">><\/span><\/span> <span class=\"token keyword\">extends<\/span> <span class=\"token class-name\"><span class=\"token constant\">T<\/span><\/span> <span class=\"token punctuation\">{<\/span>\n  <span class=\"token keyword\">public<\/span> <span class=\"token function\">say<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token operator\">:<\/span> <span class=\"token builtin\">string<\/span> <span class=\"token punctuation\">{<\/span>\n    <span class=\"token keyword\">return<\/span> <span class=\"token string\">'What time is recess?'<\/span><span class=\"token punctuation\">;<\/span>\n  <span class=\"token punctuation\">}<\/span>\n\n  <span class=\"token comment\">\/\/ ...<\/span>\n<span class=\"token punctuation\">}<\/span>\n\n<span class=\"token keyword\">const<\/span> bart<span class=\"token operator\">:<\/span> Simpson<span class=\"token operator\">&lt;<\/span>Student<span class=\"token operator\">&lt;<\/span>Person<span class=\"token operator\">>><\/span> <span class=\"token operator\">=<\/span> <span class=\"token comment\">\/\/ ...<\/span>\nbart<span class=\"token punctuation\">.<\/span><span class=\"token function\">say<\/span><span class=\"token punctuation\">(<\/span><span class=\"token punctuation\">)<\/span><span class=\"token punctuation\">;<\/span> <span class=\"token comment\">\/\/ Returns what?<\/span>\n<\/code><\/pre><p>Since <code>ctor&lt;T&gt;<\/code>&#39;s implementation of mixins does not actually break\nsingle-inheritance, there is a clear winner. The type <code>Simpson&lt;Student&lt;Person&gt;&gt;<\/code>\nmeans that <code>Simpson<\/code> extends <code>Student<\/code> which extends <code>Person<\/code>, and thus method\ndispatch would occur in that order, returning <code>D&#39;oh!<\/code>.<\/p>\n<p>If the user wanted to call the implementation on <code>Student<\/code>, there would need to\nbe a special syntax to allow it. Something like <code>bart.&lt;Student&lt;Person&gt;&gt;say()<\/code>\ncould qualify the method invocation to use a specific type in the inheritance\nhierarchy.<\/p>\n<p>This also means that <em>order of inheritance matters<\/em>, as\n<code>Simpson&lt;Student&lt;Person&gt;&gt;<\/code> is a distinct type from <code>Student&lt;Simpson&lt;Person&gt;&gt;<\/code>\nbecause calling <code>.say()<\/code> returns <code>D&#39;oh!<\/code> and <code>What time is recess?<\/code>\nrespectively. Of course, if your usage of mixins depends on their ordering, it\nis quite likely your inheritance hierarchy has larger design problems.<\/p>\n<p>Public symbols can at least be resolved unambiguously due to single-inheritance,\nbut there is still additional complexity and the possibility of bugs as a\nresult. Fortunately, if the language is\n<a href=\"https:\/\/en.wikipedia.org\/wiki\/Nominal_type_system\" target=\"_blank\">nominally typed<\/a>, <code>private<\/code>\nsymbols can always be resolved unambiguously, so this only really applies to\n<code>public<\/code> and <code>protected<\/code> symbols.<\/p>\n<h3 id=\"re-using-a-ctort\">Re-using a <code>ctor&lt;T&gt;<\/code><\/h3>\n<p>There is also the question of whether or not it is possible to reuse a <code>ctor&lt;T&gt;<\/code>\nto construct multiple subclasses. Conceptually this seems reasonable as there is\nnothing semantically wrong with that idea, but it might take extra work in the\ncompiler to support that depending on how it is implemented under the hood. You\nprobably would not want to hurt construction performance to support multiple\n<code>.construct()<\/code> calls when that would almost never happen in practice.<\/p>\n<p>Being able to reuse a <code>ctor&lt;T&gt;<\/code> would mean the compiler could not construct the\nobject in-place which may impact optimizations. It could also be possible to\nhave a distinct <code>reusableCtor&lt;T&gt;<\/code> type, though that comes with additional\ncognitive overhead.<\/p>\n<p>Relatedly, some users might reasonably ask to read or mutate the fields on a\n<code>ctor&lt;T&gt;<\/code> after it is created. I do not see any major concerns with reading the\ndata, though immutability can be desirable. Again, a distinct <code>mutableCtor&lt;T&gt;<\/code>\ncould be made, though composing it with <code>reusableCtor&lt;T&gt;<\/code>, <code>closedCtor&lt;T&gt;<\/code>, and\n<code>abstractCtor&lt;T&gt;<\/code> starts to scale somewhat poorly. Clearly the solution is to\nmodel all these features as mixins to a base <code>ctor&lt;T&gt;<\/code> object! I&#39;m joking here,\nbut I&#39;m also kind of not...<\/p>\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>Looking at constructors in modern object-oriented languages, I see quite a few\ninconsistencies and unnecessary complexities which can be improved upon. What is\npresented here is a different paradigm for thinking of and interacting with\nconstructors with one possible alternative implementation to consider. There are\nlikely other means of implementing minimal constructors without using <code>ctor&lt;T&gt;<\/code>,\nand a language designer should think of its constructor mechanisms within the\ncontext of the language as a whole rather than forcing a particular\nimplementation or ideology onto a language which has other incompatibilities.<\/p>\n<p>It is actually possible to follow the minimal constructor concept in existing OO\nlanguages. All that is really necessary is to limit constructor definitions to\nmerely assign local data and defer all other logic to a factory. Some languages\nmake this easier or harder than others, particularly when inheritance comes into\nplay. If you are using Go or Rust, you are already following this pattern, just\nsacrificing some traditional object-oriented features in the trade off.<\/p>\n<p>I mainly wanted to explore what the concept of &quot;minimal constructors&quot; means to a\nprogramming language and present a model for how it could be leveraged to\nenforce best practices without dropping existing object-oriented features. In\nthe process I found a few other &quot;interesting&quot; consequences of the design which I\nwanted to share. Try out the\n<a href=\"https:\/\/github.com\/dgp1130\/ctor-exp\" target=\"_blank\"><code>ctor-exp<\/code><\/a> package yourself\nand see what crazy patterns you can come up with.<\/p>\n<p>I believe we can <code>.construct()<\/code> something better.<\/p>\n"}]}