Skip to main content

Pretext: Text Measurement Without the DOM

via @_chenglou

Came across pretext on X this weekend and spent some time playing with it.

It solves a specific problem: calculating how tall a block of text will be at a given width, without rendering it in the DOM. Normally you'd have to put the text in a div, measure offsetHeight, and deal with the reflow cost. Pretext does it in pure JavaScript using the browser's font engine via an off-screen canvas.

Two functions. prepare(text, font) measures all the word segments once. layout(prepared, width, lineHeight) calculates the height at any width. The prepare step is the expensive one. The layout step runs in about 0.09ms for 500 texts, so you can call it on every resize without thinking about it.

Built by Cheng Lou, who created react-motion. Few KB, supports all languages including RTL and CJK, validated against the Great Gatsby rendered across browsers.

Link to Try itTry it

Type something, drag the width slider, see the numbers update. Left side is pretext (no DOM). Right side is the actual rendered text.

Text to measure
Container width400px
pretext calculated
0px
in 0.000ms
actual DOM height
0px
match
rendered at 400px
Pretext calculates how tall this text will be at any width without touching the DOM. Drag the slider to see it recalculate in real time. The left number comes from pretext. The right panel is the actual rendered text. They match.

Link to Where this is usefulWhere this is useful

Virtualized lists where you need item heights before rendering. Canvas or WebGL text where there is no DOM. Preventing layout shift by calculating dimensions before painting. AI-driven UI testing where you want to verify layout without a browser.

Where it is not useful: static sites, server-rendered pages, anything where the text is already in the DOM and you can just read offsetHeight.

Link to InstallInstall

npm install @chenglou/pretext
import { prepare, layout } from '@chenglou/pretext' const prepared = prepare('Your text here', '16px sans-serif') const result = layout(prepared, 400, 24) // width, lineHeight console.log(result.height) // pixel height

Writing this mostly so I remember to reach for it next time I need text measurement in a project. If you are building anything with virtualized lists or canvas text, worth bookmarking.

Source: github.com/chenglou/pretext