# Svelte and SvelteKit

> Typed Svelte 5 skeleton loader components with server rendering, for Svelte and SvelteKit.

To show a skeleton loader in Svelte, wrap the part of the page that loads in Dotquilt's `<LoadingRegion>`, give it a `placeholder` snippet such as `<SkeletonText lines={3} />`, and set its `state` from your data: `pending`, `refreshing` or `ready`.

`@dotquilt/svelte` wraps the same native components in typed Svelte 5 components. They register themselves, render their placeholder on the server, and take their state from your props. No configuration is needed.

```sh
npm install @dotquilt/svelte dotquilt
```

```ts
import { LoadingRegion, SkeletonText } from '@dotquilt/svelte';
```

Each component also has its own entry point, such as `@dotquilt/svelte/region`, if you prefer to import only what a page uses.

## State comes from your data

A region needs only two things from you: whether the data is `pending`, `refreshing` or `ready`, and a `cycle` naming the current request. Keep the request in your own state:

- **Start a new cycle per request**, such as the id you are loading. A stale answer for an older cycle can't settle a newer one.
- **Use `refreshing`** when you already show data and are fetching a newer copy: the content stays visible and usable.
- **On an error**, show your message with `state="ready"` and `timing={{ duration: 0 }}`, so it replaces the placeholder at once.

```svelte title="src/lib/TeamList.svelte"
<script lang="ts">
import { LoadingRegion, SkeletonCircle, SkeletonLine } from '@dotquilt/svelte';
import { onMount } from 'svelte';

interface Member {
  name: string;
  role: string;
}

let status = $state<'loading' | 'done' | 'failed'>('loading');
let members = $state<Member[]>([]);
let cycle = $state(0);
let handovers = $state(0);
let latest: AbortController | undefined;

function load() {
  // Only the latest request may update the list.
  latest?.abort();
  const request = new AbortController();
  latest = request;
  status = 'loading';
  fetch('/api/team', { signal: request.signal })
    .then((response) => {
      if (!response.ok) throw new Error(`Request failed: ${response.status}`);
      return response.json() as Promise<Member[]>;
    })
    .then((list) => {
      members = list;
      status = 'done';
    })
    .catch(() => {
      if (!request.signal.aborted) status = 'failed';
    });
}

function reload() {
  cycle++;
  load();
}

onMount(() => {
  load();
  return () => latest?.abort();
});
</script>

<section>
  <h2>Members</h2>
  <button type="button" onclick={reload}>Reload</button>
  <!-- An error replaces the placeholder at once, without the handoff. -->
  <LoadingRegion
    aria-label="Team members"
    state={status === 'loading' ? 'pending' : 'ready'}
    cycle={String(cycle)}
    timing={status === 'failed' ? { duration: 0 } : undefined}
    onHandoffEnd={() => handovers++}
  >
    {#snippet placeholder()}
      {#each [0, 1, 2] as row (row)}
        <div class="member-skeleton">
          <SkeletonCircle />
          <SkeletonLine style="width: 45%" />
          <SkeletonLine style="width: 30%" />
        </div>
      {/each}
    {/snippet}
    {#if status === 'done'}
      {#each members as member (member.name)}
        <div class="member">
          <span class="avatar"></span>
          <h3>{member.name}</h3>
          <p>{member.role}</p>
        </div>
      {/each}
    {:else if status === 'failed'}
      <p role="alert">We couldn't load the team. Try again later.</p>
    {/if}
  </LoadingRegion>
  <p class="note">Handovers: {handovers}</p>
</section>
```

## SvelteKit

The components render on the server too: the placeholder is in the first HTML, before any JavaScript runs. Hydration keeps it, because the elements register only after the component mounts. Client-side navigation works the same: a loader on the next page starts fresh, and its listeners go when the page does.

A `TextLoader`'s value is a snippet, whose text the server can't read ahead of time. Give it a `mask` with the shape of the answer, so the placeholder in the server HTML has that shape:

```svelte title="src/lib/RevenueTotal.svelte"
<script lang="ts">
import { TextLoader } from '@dotquilt/svelte';
import { onMount } from 'svelte';

const money = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  maximumFractionDigits: 0,
});
let total = $state<number | null>(null);

onMount(() => {
  const request = new AbortController();
  fetch('/api/revenue', { signal: request.signal })
    .then((response) => response.json() as Promise<{ total: number }>)
    .then((body) => {
      total = body.total;
    })
    .catch(() => {});
  return () => request.abort();
});
</script>

<p class="kpi">
  <!-- The mask is the shape of the answer: the placeholder shows it in marks. -->
  <TextLoader
    aria-label="Revenue this month"
    mask="$00,000"
    state={total === null ? 'pending' : 'ready'}
    >{total === null ? '' : money.format(total)}</TextLoader
  >
</p>
```

## Events and the element

Events are callback props: `onHandoffStart`, `onHandoffEnd`, `onHandoffCancel` and `onLoaderError`, each with the native `CustomEvent`. `event.detail.reason` says how a handoff ended. `bind:element` gives you the native element, if you need its methods.

To style Dotquilt's elements from a component, use `:global(dotquilt-skeleton-text)` in its `<style>`: Svelte's scoped CSS doesn't reach elements another component renders. And while pending, render no content in the region (`{#if}` on the data), so the placeholder holds its own size.

## Styles and CSP

By default each component adds its styles inline, inside its element. If your site has a Content Security Policy, pass a `stylePolicy` to every component: a nonce (in SvelteKit, the value of `%sveltekit.nonce%`), or an external stylesheet from `@dotquilt/svelte/styles/`. See [Content Security Policy](/docs/guides/csp/).

## The native elements in Svelte

You can also use the native elements directly, without `@dotquilt/svelte`: register them in the browser before they render, and Svelte sets objects such as a table's `columns` as properties. The native elements have no placeholder in the server HTML: it appears once they register.
