@chenglou/pretext
Fast multiline text measurement and layout without DOM reflow
Measuring text height in the browser requires querying the DOM โ calling getBoundingClientRect() or reading offsetHeight forces the browser to perform a full layout reflow, one of the most expensive operations possible. In virtualised lists, dynamic text containers, or layouts where text flows around obstacles, you may need thousands of these measurements per frame. DOM-based measurement makes that cost prohibitive.
Pretext separates the expensive part (measuring character widths via Canvas) from the cheap part (computing line breaks via arithmetic). Call prepare() once per text string โ it measures every segment with Canvas and caches the results. Then call layout() as many times as you like at any width, entirely in arithmetic, with no DOM access at all. Prepare once, layout many times.
Install @chenglou/pretext
npm install @chenglou/pretext
import { prepare, layout } from '@chenglou/pretext';Use it when
Use pretext when you need to know text dimensions before rendering โ virtualised scrolling lists where you must know item heights upfront, text flowing around images or arbitrary obstacles, dynamic subtitle/caption positioning, detecting content overflow at build time, or any animation that requires text metrics on every frame.
Skip it when
Pretext only measures plain text โ it cannot handle HTML markup, inline images, or mixed rich content. For simple cases where you measure a single element once on mount, the browser's built-in ResizeObserver or getBoundingClientRect is simpler and sufficient. Pretext's two-phase API adds conceptual overhead that is only justified when measurements are frequent or happen before render.
Ready to explore the full API?
See every class, function, and relationship in an interactive graph.