App
Web components
A web component can paint before its JavaScript loads when the server renders it. Put its server output inside {@html} in a host that stays Svelte markup, and the island around it still hydrates.
On this page
- Host rendering
- Compatibility
- rewrite() fallback
- Pitfalls
- Add the component’s own classes to class
- Write the host id the library expects
- Load definitions after the page is parsed
- Count the CSS each copy carries
- A host kept across a navigation keeps its shadow root
- A closed shadow root is lost on a copied element
- Svelte gaps
A web component usually renders in the browser, once its definition loads. Until then its host is empty, or shows unstyled light DOM. Many component libraries can also render on the server: they give you HTML for the component, often as a declarative shadow root (<template shadowrootmode="open">). The browser turns that template into a real shadow root while it parses the page, so the component paints before any JavaScript runs.
There are two ways to put that server output on an ogygia page. This page covers the simple one, the {@html} host pattern. The other is a pass over the HTML after Svelte renders it, rewrite() from @ogygia/rewrite.
In the example, a Card component wraps a library’s <x-card>. On the server, renderCard() returns the card’s declarative shadow root, and {@html} puts it inside the host. In the browser, {@html} gets an empty string.
<script lang="ts">
import { browser } from '$app/environment';
import { renderCard } from '$lib/x-card/render';
let { title }: { title: string } = $props();
let open = $state(false);
</script>
<x-card {title} onclick={() => (open = !open)}>
{@html browser ? '' : renderCard({ title })}
<p>{open ? 'Open' : 'Closed'}</p>
</x-card>Host rendering
Write the host element in your Svelte markup as usual, as Card does above. Put the component’s server output inside it with {@html}, and render nothing there in the browser.
- The host stays Svelte markup. Its attributes, event handlers and
bind:thisare Svelte’s, as on any element. - The server output goes inside
{@html}. On the server,renderCard()returns the declarative shadow template. The browser’s parser turns it into the host’s shadow root, so nothing of it is left in the light DOM. Keep the output to that template alone: a node it leaves in the light DOM is one Svelte doesn’t expect, and the island fails hydration. - In the browser the
{@html}is empty. When the island hydrates, Svelte finds nothing to compare there.browseris a build-time constant, so the browser build drops therenderCard()call, and the renderer with it when its module has no side effects. - The light DOM is Svelte’s. The
<p>in the example is slotted into the shadow root like any other child, and it stays reactive.
When the component’s definition loads, it finds its server shadow root already there and adopts it instead of rendering again. How it does that is up to the library; see Avoid the traps.
The pattern works in a page’s markup, inside an island (any wake), inside a lake and in a server island’s answer. It also works after a navigation with the SPA router: the next page is parsed the same way the first one was, so its hosts get their shadow roots too.
Load the component definitions from src/app.html, so every page has them. The SPA router doesn’t run scripts from the next page, in its <head> or its body. A definition script in one page’s <svelte:head> would run on a full load of that page, but never for a visitor who reaches it by a client navigation, and its <x-card> would stay undefined. A module script runs after the page is parsed (see Load definitions after the page is parsed).
In the example, src/app.html loads the definitions, and a page uses Card as an island.
<head>
<meta charset="utf-8" />
%sveltekit.head%
<script type="module" src="/x-card/define.js"></script>
</head><script>
import Card from '$lib/Card.svelte' with { wake: 'visible' };
</script>
<Card title="Shipping" />Compatibility
The pattern fits a component when both of these are true:
- It renders into a shadow root. Its server output is a declarative shadow template and nothing else.
- Its light DOM is Svelte’s, or empty. The host’s children are what you wrote in Svelte, and the component only shows them through
<slot>s. It doesn’t add, move or remove children of its own.
Most design-system components built on shadow DOM fit: buttons, cards, badges, icons, dialogs.
rewrite() fallback
Use a rewrite with rewrite() for a component that does any of these:
- It renders into its light DOM. A “scoped” component, or one with no shadow root, writes its markup next to your children. The server output leaves nodes in the light DOM, and Svelte’s hydration trips on them.
- Its server render reads its children. A carousel that counts its slides, or a list that sorts its items, needs the children while it renders. Inside
{@html}the renderer runs before the children exist, so it sees none. - It changes its light DOM when it upgrades. A component that adds a backdrop, wraps its children or reorders them changes nodes Svelte’s hydration reads. See DOM ownership.
rewrite() runs after Svelte renders, sees each element whole, and in the browser puts back what hydration needs before anything hydrates. One site can use both: {@html} for the components that fit, rewrite() for the rest.
Pitfalls
Add the component’s own classes to class
Svelte writes the whole class attribute of a custom element when the island hydrates, and again on every change, so a class the component added to its own host is removed. Many libraries add one when they upgrade (hydrated, a mode, a state) and use it in their CSS, say to hide a host until it’s ready.
Add those classes to your own class list, so Svelte writes them too. A class that depends on the component’s props has to be worked out the same way on the server and in the browser, without the renderer.
Write the host id the library expects
Some libraries adopt a server shadow root only when the host carries an id their server render wrote (an attribute such as data-render-id, with matching ids inside the template). Without it, the component renders again over the server root, and its content shows twice. If your library’s server output puts an attribute on the host, write it on the host in Svelte, from the same inputs.
Load definitions after the page is parsed
Load the component definitions with a module script or a defer script, never with a blocking <script> in <head>. A definition that runs before the body is parsed upgrades each host as soon as its start tag is read, before the declarative template inside it. The component attaches its own shadow root, and the server’s is dropped.
Count the CSS each copy carries
A declarative shadow root holds its own <style>, so each instance carries the component’s whole stylesheet. A page with fifty buttons sends the button CSS fifty times. Compression helps, but the browser still parses every copy. For a component with many instances per page, a light-DOM render with one shared stylesheet, through rewrite(), can make the smaller page.
A host kept across a navigation keeps its shadow root
When the SPA router keeps an element across a navigation (the same tag in the same place on both pages), a web component’s host belongs to the component: ogygia keeps its live shadow root and its attributes, and doesn’t apply the next page’s server shadow root. Give the host a different id or data-key on each page when it should take the new page’s render instead.
A closed shadow root is lost on a copied element
When the router, or a region update, brings in a new element, it copies it from the next page’s HTML. An open declarative shadow root comes along. A closed one (<template shadowrootmode="closed">) doesn’t: scripts can’t read a closed root, so the copy has none, and whatever the root painted is gone. A closed root marked shadowrootclonable is the one exception.
In dev, ogygia warns closed_shadow_root_lost when this happens. Pick one of these:
- Use
shadowrootmode="open". - Have the component attach its root itself (
attachShadowin its constructor orconnectedCallback), so the copy builds it again when it connects. - Keep the element the same on both pages (the same tag in the same place, or the same
idordata-key), so the router keeps it, and its root, instead of copying it.
<script lang="ts">
import { browser } from '$app/environment';
import { renderCard } from '$lib/x-card/render';
let {
title,
active = false
}: { title: string; active?: boolean } = $props();
</script>
<x-card
class={[
'card',
active && 'active',
'hydrated'
]}
>
{@html browser ? '' : renderCard({ title })}
</x-card><script lang="ts">
import { browser } from '$app/environment';
import { renderCard } from '$lib/x-card/render';
let { title, id }: { title: string; id: string } = $props();
</script>
<x-card data-render-id={id}>
{@html browser ? '' : renderCard({ title }, { id })}
</x-card>Svelte gaps
The pattern relies on how Svelte hydrates {@html} and custom elements. The gaps that keep it from fitting every component (an {@html} whose server content left light-DOM nodes, declarative shadow roots created in the browser, and class on custom elements) are tracked in sveltejs/svelte#19264.