JavaScript Text Engine

The Pretext Library

The Pretext library is the fastest way to measure multiline text on the web. This pure JavaScript text measurement library computes line breaks, heights, and layout without touching the DOM — roughly 600× faster than traditional browser measurement. The Pretext library works in every framework, every browser, and every language.

~600×
Faster than DOM
~15KB
Gzipped bundle
0
Dependencies
MIT
Open source license

Overview

What Is the Pretext Library?

The Pretext library is a pure JavaScript/TypeScript text measurement engine created by Cheng Lou, a former React core team member now at Midjourney. Unlike traditional approaches that require the browser to render text into the DOM before you can measure it, the Pretext library splits text layout into two lightweight phases — making it the fastest text measurement library available for JavaScript.

The first phase of the Pretext library is preparation. You call prepare() once with your text and font. The Pretext library segments the text using Unicode rules and measures each segment's glyph width via the Canvas measureText() API. This typically takes 0.1–1ms depending on text length.

The second phase is layout. You call layout() with a container width and line height. The Pretext library walks the cached segment widths using pure arithmetic — no DOM access, no forced reflow. A single layout call in the Pretext library takes ~0.001ms, fast enough to run thousands of times per frame. The prepared handle is reusable: compute heights for mobile, tablet, and desktop from the same handle in three operations.

Pretext library — the fastest JavaScript text measurement library by chenglou
The Pretext library on GitHub (github.com/chenglou/pretext) — 23.6k stars, MIT-licensed, pure TypeScript
Pretext library — get started in 4 lines
$ npm install @chenglou/pretext

import { prepare, layout } from '@chenglou/pretext'

const prepared = prepare('Your text', '16px Inter')
const { height, lineCount } = layout(prepared, 400, 24)

Why Choose This Library

Pretext Library Features

The Pretext library was designed from the ground up for performance and developer ergonomics. Here is what makes the Pretext library the best choice for text measurement in JavaScript applications.

Zero DOM Access

The Pretext library never reads from or writes to the DOM during layout. After the initial Canvas measurement, every subsequent operation is pure arithmetic. This eliminates forced synchronous layout, reflow, and layout thrashing — the three biggest performance killers in text-heavy applications.

Framework-Agnostic

The Pretext library is a standalone JavaScript module with zero dependencies. Import it into React, Vue, Svelte, Angular, or plain JavaScript. The Pretext library works identically in every environment — client-side, server-side, or Web Workers.

Full Unicode & i18n Support

The Pretext library uses Intl.Segmenter for Unicode-aware text segmentation. CJK, Arabic, Hebrew, Thai, Korean, and mixed-script text are all measured accurately with the same API. The Pretext library handles bidirectional text and complex scripts without special-casing.

Sub-Microsecond Layout

Each layout() call in the Pretext library takes approximately 0.001ms — pure arithmetic over cached glyph widths. You can call layout() thousands of times per animation frame. This makes the Pretext library ideal for real-time reflow, responsive resizing, and interactive typography.

Variable-Width Lines

The Pretext library supports per-line width control via layoutNextLine(). Text can reflow around obstacles, follow irregular shapes, or adapt to complex editorial layouts. This is the same technique used in magazine-style text wrapping and creative typography projects built with the Pretext library.

TypeScript-First

The Pretext library is written in TypeScript with full type definitions. Every function, parameter, and return type is strongly typed. IDE autocompletion and type checking work out of the box — no @types package needed when using the Pretext library in your project.

Performance Comparison

Pretext Library vs DOM Measurement

Traditional DOM measurement creates invisible elements, renders text, reads the computed height, then removes the element. The Pretext library eliminates this entire cycle. Here is how the Pretext library compares to standard approaches.

AspectDOM MeasurementPretext Library
Speed per measurement0.5–2ms (forced reflow)~0.001ms (pure arithmetic)
DOM access requiredYes — creates hidden elementsNo — zero DOM reads/writes
Layout thrashingYes — triggers browser reflowNever — no reflow possible
SSR / Web Worker supportNo — requires browser DOMYes — works everywhere
Bundle sizeBrowser built-in (but slow)~15KB gzipped, 0 deps
Multiple widths from same textRe-render for each widthReuse handle — instant
Unicode & CJK supportDepends on browser renderingIntl.Segmenter — accurate

Applications

Pretext Library Use Cases

The Pretext library shines wherever text measurement is a bottleneck. From virtual scrolling to creative typography, here are the most common ways developers use the Pretext library in production.

📜

Virtual Scrolling

Pre-compute heights for thousands of variable-height list items using the Pretext library. No DOM elements needed. Works with React Virtuoso, TanStack Virtual, and any virtualization library for 60fps scrolling.

💬

Chat & AI Interfaces

Predict message bubble heights with the Pretext library before streaming AI responses finish rendering. Eliminate layout shift and jumpiness. Tight-wrap bubbles to minimize wasted whitespace on mobile.

📊

Dashboards & Data Tables

Size chart tooltips, table cells, and card layouts with the Pretext library — no forced synchronous reflow. Keep 60fps even with hundreds of visible text elements updating in real time.

📱

Responsive Layouts

Use the Pretext library to compute text heights at multiple breakpoints from a single prepare() call. Mobile, tablet, and desktop — three arithmetic operations from the same handle, zero reflows.

🎨

Creative Typography

Build editorial layouts where text flows around obstacles, magazine-style multi-column spreads, or particle-driven ASCII art. The Pretext library gives you per-line control that CSS alone cannot achieve.

🌍

Multilingual Content

The Pretext library measures CJK, Arabic, Hebrew, Thai, Korean, and mixed-script text with the same two-function API. Unicode segmentation and bidirectional text are handled automatically.

API

Pretext Library API Reference

The Pretext library exposes a small, focused API. Every function in the Pretext library serves a specific purpose — preparation or layout. Here is the complete function reference.

FunctionPhasePurpose
prepare(text, font)PrepareSegment and measure text. Returns opaque handle.
prepareWithSegments(text, font)PrepareLike prepare(), but exposes segment data for advanced use.
layout(prepared, width, lineHeight)LayoutCompute line count and total height. Pure arithmetic.
layoutWithLines(prepared, width, lineHeight)LayoutLike layout(), plus each line's text and width.
layoutNextLine(prepared, cursor, width)LayoutLay out one line at a time. Variable width per line.
walkLineRanges(prepared, width, cb)LayoutIterate line boundaries without building strings.

Quick Start

Getting Started with the Pretext Library

Installing the Pretext library takes one command. The Pretext library ships as a single npm package with zero dependencies. Follow these three steps to start using the Pretext library in your project.

1

Install the Pretext Library

Add the Pretext library to your project with npm, pnpm, or yarn. The package is @chenglou/pretext — approximately 15KB gzipped with zero dependencies.

2

Prepare Your Text

Call prepare(text, font) once per text+font pair. The Pretext library segments the text and measures glyph widths via Canvas. Store the handle for reuse across multiple layout calls.

3

Layout at Any Width

Call layout(handle, width, lineHeight) to get the height and line count. The Pretext library computes this with pure arithmetic in ~0.001ms. Reuse the same handle for different container widths.

Start Using the Pretext Library

The Pretext library is open source, MIT-licensed, and ready for production. Try it in the interactive playground, explore community demos, or dive into the source code on GitHub. Join thousands of developers already using the Pretext library for fast, DOM-free text measurement.

The Pretext library is created by Cheng Lou. Read more about the GitHub Pretext ecosystem.

Pretext Library — The Fastest JavaScript Text Measurement Library