Site / foldkit-site

Code-splitting routes

Combine Bundle.lazy (from foldkit-bundle) with Site.placement so a route's update and view live in a separate bundler chunk while its Model, Messages, and init stay in the boot bundle:

ts
import { Site, fetchCode } from 'foldkit-site'

const Account = Bundle.lazy(
  { name: 'Account', Model: AccountModel, Message: AccountMessage, init },
  () => import('./account.body.js').then(chunk => chunk.body),
)
const AccountPage = Site.placement(AccountNode, Account, {
  link: Link.field<Model>()('account', Link.wrapper(Message.GotAccountMessage)),
  changed: () => AccountMessage.Arrived(),
})
const Routing = Site.routing<Model, Message, AppRoute, RemoteClient>({
  // ...site, route, parse, tags, and completed as above
  pages: [AccountPage],
  preload: { links: pointedLinks(), intended: Message.PointedAtLink, read, code: fetchCode },
})
// Pass `lazy: model => Routing.codeFor(model.route)` to SSR.entry and SSR.hydrate.

Each lazy route chunk loads once on whichever happens first:

  1. Link hover or focus: preload's code: fetchCode loads Routing.codeFor(there).
  2. Server render: SSR.entry's lazy loads Routing.codeFor(model.route).
  3. Hydration: SSR.hydrate's lazy loads the chunks for the resumed Model.
  4. In-app navigation: Bundle.lazy loads the chunk when changed runs.
  5. Client-only start: init: () => Routing.boot(model) dispatches route arrival to load the starting route's chunk.

Lazy placements require a changed handler so arriving via Back or keyboard shortcuts still triggers chunk loading. See examples/auth's /account route for bundle-size measurements and chunking configuration.

Limits

  • Single-screen apps: A one-route app needs only a Foldkit Router, not a route tree.
  • Bundles with OutMessages: Use Bundle.at and Link.child directly; Site.placement covers parent-wrapped Bundles without onOut.
  • Cross-node history rules: history inspects transitions within one node; moves between distinct nodes always push a history step.
  • Layout-level Surfaces: Attach Surfaces to individual route nodes; Surfaces spanning multiple route tags are not supported.
  • Locales and themes: Model locales as route params when needed; keep UI themes as user preferences outside the route tree.

Next