Skip to main content
Pretext is a pure JavaScript/TypeScript library that measures text height and lays out paragraphs without touching the DOM. Instead of triggering expensive layout reflows via getBoundingClientRect or offsetHeight, Pretext uses canvas measureText with cached segment widths so your resize logic stays under a millisecond.

Installation

Install via npm and get up and running in minutes.

Quickstart

Measure your first paragraph height with a working code example.

API Reference

Full reference for every exported function and type.

Core Concepts

Understand the two-phase architecture and why it’s fast.

Why Pretext?

DOM-based text measurement forces synchronous layout reflow. When many components independently call getBoundingClientRect or offsetHeight, each read triggers a full document reflow — easily costing 30ms+ per frame for 500 text blocks. Pretext solves this with a two-phase approach:
1

Prepare once

Call prepare(text, font) when text first appears. It segments the text, measures each word via canvas, caches widths, and returns an opaque handle. About 19ms for a batch of 500 texts.
2

Layout on every resize

Call layout(prepared, maxWidth, lineHeight) on every resize event. Pure arithmetic over cached widths — no canvas, no DOM, no allocations. About 0.09ms for the same 500-text batch.
3

Render with full control

Use the rich line APIs (layoutWithLines, layoutNextLine, walkLineRanges) to render to Canvas, SVG, WebGL, or any custom engine.

Key features

Zero DOM reads

No getBoundingClientRect, no offsetHeight, no layout reflow. Text measurement happens entirely in JavaScript.

All languages

CJK per-character breaking, Arabic bidi, Thai word segmentation, emoji correction, and mixed-script punctuation rules.

Browser-accurate

Validated against Chrome, Safari, and Firefox with a 7,680-case regression suite — currently 7680/7680 on all three.

Rich layout APIs

From simple height prediction to line-by-line streaming with variable widths — covering virtualization, masonry, text wrapping around floats, and shrinkwrap layouts.

Build docs developers (and LLMs) love