← back to index

05. islands, server-orchestrated, zero client JS

A page with three islands. The server holds the connection open and races three async data sources in parallel. Whichever finishes first flushes its <template for> first. No JS runs on the page.

news

weather

builds

island timings: weather ~600ms, news ~1.4s, builds ~2.4s. Watch them fill in order of completion.

learn more

source

Everything the server runs for this example. Each file links to GitHub so you can copy or fork it.

handler.ts/app/src/examples/05-islands/handler.ts
import { sleep, streamingResponse } from "../../lib/streaming.ts";
import { loadShell, tryStatic } from "../../lib/files.ts";

const SHELL = loadShell(import.meta.url);
const SUFFIX = `</body></html>`;

interface Island {
  name: string;
  delayMs: number;
  body: string;
}

const ISLANDS: Island[] = [
  {
    name: "news",
    delayMs: 1400,
    body: `<ul style="margin:0;padding-left:1.2rem;font-size:.9rem;">
  <li>chrome 148: declarative partial updates lands</li>
  <li>safari 26.2: navigation api</li>
  <li>firefox: still no opinion on dpu</li>
</ul>`,
  },
  {
    name: "weather",
    delayMs: 600,
    body: `<p style="margin:0;font-size:2rem;font-weight:700;">12°c</p>
<p style="margin:0;color:var(--muted);font-size:.85rem;">liverpool, cloudy</p>`,
  },
  {
    name: "builds",
    delayMs: 2400,
    body: `<ul style="margin:0;padding-left:1.2rem;font-size:.85rem;">
  <li>aifocus / main &mdash; <span style="color:#1d8b3e;">green</span></li>
  <li>agent-do / main &mdash; <span style="color:#1d8b3e;">green</span></li>
  <li>declarative-partial-updates-experiments / main &mdash; <span style="color:#b87b00;">running</span></li>
</ul>`,
  },
];

async function fetchIsland(island: Island): Promise<{ name: string; body: string }> {
  await sleep(island.delayMs);
  return { name: island.name, body: island.body };
}

export default function handle(_req: Request, path: string): Response | Promise<Response> {
  if (path === "/" || path === "/index.html") {
    return streamingResponse(async (write) => {
      await write(SHELL);
      const pending = ISLANDS.map((island) =>
        fetchIsland(island).then((r) => write(`<template for="${r.name}">${r.body}</template>`))
      );
      await Promise.all(pending);
      await write(SUFFIX);
    });
  }
  return tryStatic(import.meta.url, path) ?? new Response("Not found", { status: 404 });
}

open on GitHub →

index.html/app/src/examples/05-islands/index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>05 · Islands (zero JS)</title>
  <link rel="stylesheet" href="/public/styles.css">
</head>
<body>
<main>
  <p class="crumbs"><a href="/">&larr; back to index</a></p>
  <h1>05. islands, server-orchestrated, zero client JS</h1>
  <p class="lede">A page with three islands. The server holds the connection open and races three async data sources in parallel. Whichever finishes first flushes its <code>&lt;template for&gt;</code> first. No JS runs on the page.</p>

  <section class="island-grid">
    <article class="island" id="island-news">
      <h3>news</h3>
      <section>
        <?start name="news">
          <div class="skeleton"></div>
          <div class="skeleton"></div>
          <div class="skeleton sm"></div>
        <?end>
      </section>
    </article>

    <article class="island" id="island-weather">
      <h3>weather</h3>
      <section>
        <?start name="weather">
          <div class="skeleton lg"></div>
          <div class="skeleton sm"></div>
        <?end>
      </section>
    </article>

    <article class="island" id="island-builds">
      <h3>builds</h3>
      <section>
        <?start name="builds">
          <div class="skeleton"></div>
          <div class="skeleton"></div>
          <div class="skeleton"></div>
        <?end>
      </section>
    </article>
  </section>

  <p style="margin-top:1.5rem;color:var(--muted);font-size:.85rem;">island timings: weather ~600ms, news ~1.4s, builds ~2.4s. Watch them fill in order of completion.</p>

  <section class="refs">
    <h3>learn more</h3>
    <ul>
      <li><a href="https://developer.chrome.com/blog/declarative-partial-updates?hl=en" target="_blank" rel="noopener">Chrome blog: Declarative Partial Updates</a></li>
      <li><a href="https://github.com/WICG/declarative-partial-updates/blob/main/patching-explainer.md" target="_blank" rel="noopener">WICG explainer: patching</a> <span class="note">— Out-of-order template flushing is exactly what this example does.</span></li>
      <li><a href="https://jasonformat.com/islands-architecture/" target="_blank" rel="noopener">Jason Miller: Islands Architecture</a> <span class="note">— The original 2020 essay introducing the term.</span></li>
      <li><a href="https://github.com/GoogleChromeLabs/web-perf-demos/blob/main/patching-demos/photo-album-server.js" target="_blank" rel="noopener">photo-album demo</a> <span class="note">— A larger example of out-of-order template flushing.</span></li>
    </ul>
  </section>

  <!-- source-viewer goes here -->

  <footer class="byline">made by <a href="https://paul.kinlan.me/" target="_blank" rel="noopener">Paul Kinlan</a></footer>
</main>

open on GitHub →

lib/streaming.ts/app/src/lib/streaming.ts
export class StreamAborted extends Error {
  constructor() {
    super("stream aborted by client");
    this.name = "StreamAborted";
  }
}

export type ChunkSource = (write: (chunk: string) => Promise<void>) => Promise<void>;

const encoder = new TextEncoder();

export function streamingResponse(
  source: ChunkSource,
  contentType = "text/html; charset=utf-8",
): Response {
  let aborted = false;
  const body = new ReadableStream<Uint8Array>({
    async start(controller) {
      const write = async (chunk: string) => {
        if (aborted) throw new StreamAborted();
        try {
          controller.enqueue(encoder.encode(chunk));
        } catch {
          aborted = true;
          throw new StreamAborted();
        }
      };
      try {
        await source(write);
      } catch (err) {
        if (!(err instanceof StreamAborted)) console.error("stream source error", err);
      } finally {
        if (!aborted) {
          try {
            controller.close();
          } catch {
            // already closed
          }
        }
      }
    },
    cancel() {
      aborted = true;
    },
  });
  return new Response(body, {
    headers: {
      "content-type": contentType,
      "cache-control": "no-store",
      "x-content-type-options": "nosniff",
    },
  });
}

export function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

open on GitHub →

lib/files.ts/app/src/lib/files.ts
// File helpers for examples: read sibling files, render the page shell with the
// source viewer injected, and serve sibling static assets (CSS/JS/HTML) on demand.

import { sourceBlock } from "./source.ts";

const MIME: Record<string, string> = {
  css: "text/css; charset=utf-8",
  js: "application/javascript; charset=utf-8",
  html: "text/html; charset=utf-8",
  svg: "image/svg+xml",
  json: "application/json; charset=utf-8",
};

function dirFor(handlerUrl: string): string {
  return new URL(".", handlerUrl).pathname;
}

export function readSibling(handlerUrl: string, name: string): string {
  return Deno.readTextFileSync(dirFor(handlerUrl) + name);
}

// Reads a sibling HTML file. The marker `<!-- source-viewer goes here -->` is replaced
// with the source-viewer block. Extra named placeholders ({{name}}) can be supplied via `vars`.
const SOURCE_MARKER = "<!-- source-viewer goes here -->";

export function loadShell(
  handlerUrl: string,
  name = "index.html",
  vars: Record<string, string> = {},
): string {
  let raw = readSibling(handlerUrl, name);
  raw = raw.replace(SOURCE_MARKER, sourceBlock(handlerUrl));
  for (const [k, v] of Object.entries(vars)) {
    raw = raw.replaceAll(`{{${k}}}`, v);
  }
  return raw;
}

// Try to serve a sibling static file from the example folder. Returns null when the
// file is missing, the path escapes the folder, or the path is empty.
export function tryStatic(handlerUrl: string, requestPath: string): Response | null {
  const safe = requestPath.replace(/^\/+/, "");
  if (!safe || safe.includes("..")) return null;
  // Never let the browser fetch handler.ts or README.md through this fallback.
  if (safe === "handler.ts" || safe === "README.md") return null;
  try {
    const content = Deno.readFileSync(dirFor(handlerUrl) + safe);
    const ext = safe.split(".").pop() ?? "";
    return new Response(content, {
      headers: {
        "content-type": MIME[ext] ?? "application/octet-stream",
        "cache-control": "no-store",
      },
    });
  } catch {
    return null;
  }
}

open on GitHub →