# Lazy and Suspense

Source: https://signy.dev/documentation/1/templates/lazy-and-suspense/

Load components when they are needed.

## lazy()

`lazy(importer)` takes a function that returns a module promise, usually a dynamic `import()`, and gives back a component that loads the first time it renders. The module's default export is a component class, or a function component that takes props and returns nodes.

```js
// reports.js
export default class Reports extends Component { /* ... */ }

// app.js
const LazyReports = lazy(() => import('./reports.js'));
html`<${LazyReports} year=${2026} />`;
```

`minLoadTime` keeps the fallback up for at least that many milliseconds, so a fast load does not flash.

## Suspense

A lazy component must render inside a `Suspense` boundary. The boundary shows its fallback until every lazy component and resource inside it is ready. Pass `children` as a function.

```js
const { Component, Signal, application, html, lazy, Suspense, Show } = Signy;

class Chart extends Component {
  render() {
    return html`<p class="alert success">The chart module loaded.</p>`;
  }
}

// A real app would pass () => import("./chart.js")
const LazyChart = lazy(() =>
  new Promise((resolve) => setTimeout(() => resolve({ default: Chart }), 800)),
);

class Report extends Component {
  open = new Signal(false);

  render() {
    return html`
      <button onClick=${() => (this.open.value = true)}>Show the chart</button>
      ${Show({
        when: () => this.open.value,
        children: () => Suspense({
          fallback: html`<p aria-busy="true">Loading the chart</p>`,
          children: () => html`<${LazyChart} />`,
        }),
      })}
    `;
  }
}

application(Report).mount("#lazy-suspense");
```

## Preloading

`LazyChart.preload()` starts loading without rendering, and `preloadAll([a, b])` loads several. Call them on hover or when the browser is idle, and the component renders at once when it is needed.

```js
link.addEventListener('pointerenter', () => LazyChart.preload());
requestIdleCallback(() => preloadAll([LazyChart, LazyTable]));
```

Each lazy component also exposes its `state` and `error` as signals, and `loading()`.
