Code splitting
lazy(loader) defines a component whose code loads on first render.
lazy(loader) defines a component whose code loads on first render. The loader
runs once however many times the component renders; while it loads, the nearest <Suspense> shows its
fallback. Component.preload() starts the load without rendering, so a route link can warm the chunk on
hover. With Vite, import() is a split point automatically.
src/heavy.tsxtsx
export default function Heavy() {
return <p>heavy content</p>;
}
src/lazy-panel.tsxtsx
import { lazy, Suspense } from "@shadow-js/web";
export const loads = { count: 0 };
export const Heavy = lazy(() => {
loads.count += 1;
return import("./heavy");
});
export function Page() {
return (
<Suspense fallback={<em>loading chunk</em>}>
<Heavy />
<Heavy />
</Suspense>
);
}
Split by route (a lazy component per route component) and by features that most visitors never open
(editors, charts, dialogs with heavy content). Do not split small components: each chunk costs a
request.