For thirty years, web developers have lived with a compromise nobody questioned. Measuring text dimensions in a browser requires either touching the DOM (triggering an expensive layout reflow) or spinning up a Canvas 2D context. Both approaches are orders of magnitude slower than they should be.
Pretext, a JavaScript/TypeScript library by Cheng Lou (the creator of react-motion and former React core developer at Facebook), eliminates this bottleneck entirely. By using the browser's Canvas API to measure text segments once, then computing layout through pure arithmetic, it achieves text measurement that is up to 500 times faster than traditional DOM methods.
The GitHub repo crossed 25,000 stars in four days. Cheng Lou's announcement tweet accumulated over 60,000 likes and 21 million views. For teams building multilingual SaaS products, the implications are massive.
This challenge is particularly acute in modern B2B prospecting applications. When sales teams compose personalized email sequences in an editor like Emelia's, every text modification requires a layout recalculation to ensure the subject line won't truncate, the message body displays correctly in the preview pane, and call-to-action buttons remain visible. Multiply this by the number of A/B variants being tested and the number of target languages, and text measurement becomes a first-class performance concern.
Modern front-end frameworks like React, Vue, and Svelte inadvertently amplify the problem. Their declarative rendering model, where the UI rebuilds on every state change, multiplies the number of required text measurements. A table component that re-renders after a sort or filter operation can trigger hundreds of simultaneous text measurements, each causing a reflow. By decoupling text measurement from the browser's rendering cycle, Pretext integrates naturally into these reactive architectures without creating bottlenecks.
DOM measurement (getBoundingClientRect) works by injecting a hidden element into the document tree, setting its content, and asking the browser for computed dimensions. This triggers a layout reflow a complete recalculation of every element's position and size on the page. On a complex page, each reflow can take several milliseconds.
Canvas measurement (measureText) avoids the reflow by using the Canvas 2D rendering context instead. It's faster, but still carries significant overhead: it must initialize the font rendering engine, load glyph data, apply kerning rules, and handle complex text shaping for non-Latin scripts.
At scale, both approaches become serious performance bottlenecks. A campaign analytics dashboard displaying 500 rows of prospect data needs to measure every cell for column auto-sizing. With DOM measurement, this operation can block the main thread for over 200 milliseconds roughly 12 dropped frames at 60fps, creating a visible UI freeze.
Pretext separates text measurement into two distinct phases. prepare() uses the browser's canvas.measureText() API to measure each text segment once, respecting Unicode segmentation rules via Intl.Segmenter. It handles all scripts natively: Latin, CJK, Arabic RTL, emoji sequences, Thai, Hindi, and more. Results are cached.
layout() then computes line count, total height, and break positions through pure arithmetic. No DOM, no reflow. Each layout() call takes approximately 0.05 milliseconds for 1,000 items. When the user resizes their window, only layout() runs prepare() doesn't need to re-execute.
import { prepare, layout } from '@chenglou/pretext';
// prepare() measures segments via Canvas (runs once)
const prepared = prepare(
'Automate your B2B prospecting workflow in minutes',
'16px Inter'
);
// layout() is pure arithmetic (runs in microseconds)
const { height, lineCount } = layout(
prepared,
400, // container width in px
24 // line height in px
);
console.log(height); // → 48
console.log(lineCount); // → 2
// Re-layout at a different width is essentially free
const narrow = layout(prepared, 240, 24); // → 3 linesThe cache invalidation strategy is equally important. Pretext maintains an internal cache keyed on font configuration and text content. If the same text string is measured twice with the same font settings, the second call returns instantly from cache without touching the Canvas API. For applications that display recurring text patterns think status labels in a CRM dashboard ('Active', 'Pending', 'Closed') or standard email signatures this caching eliminates redundant work automatically.
This two-phase design is more than a performance trick it's an architectural decision that enables entirely new patterns. Because prepare() and layout() are separated, you can measure text segments once during application initialization and then recompute layouts thousands of times as the user interacts with the interface. In a responsive email builder, for example, the text preparation happens when the user opens a template, and layout recalculations happen instantly as they resize panels, switch between mobile and desktop previews, or toggle between language versions.
The full API is documented on the official GitHub repository and on pretextjs.dev. The library is available on npm as @chenglou/pretext.
The performance numbers show dramatic improvements across every scenario tested. For 1,000 consecutive text measurements:
Method | Time (1,000 measurements) | Reflows | Speed vs DOM |
|---|---|---|---|
DOM (getBoundingClientRect) | ~94 ms | 1,000 reflows | 1x (baseline) |
Canvas (measureText) | ~5 ms | 0 reflows | ~19x |
Pretext (prepare + layout) | ~0.05 ms | 0 reflows | ~500x |
Pretext (layout only) | ~0.02 ms | 0 reflows | ~4,700x |
The 500x speedup over DOM measurement is not marketing hyperbole. It's the natural result of eliminating all browser rendering overhead. In practical terms, 1,000 DOM measurements equate to roughly 6 dropped frames at 60fps. Pretext causes zero perceptible slowdown.
Every email client truncates subject lines at a different pixel width. Gmail desktop shows roughly 520 pixels, Outlook about 440, Apple Mail around 480, and mobile clients are even more restrictive. Without accurate measurement, email marketers are essentially guessing.
With Pretext, real-time truncation previews for every major email client become feasible directly in the composition interface. This is especially valuable for platforms operating across multiple languages. Emelia supports campaigns in over 40 languages, and a subject line that works perfectly in English might truncate awkwardly in German (where compound words can be extremely long) or Finnish.
Modern email editors need to measure text constantly. Every keystroke potentially requires a layout recalculation: does the text overflow its container? Should it wrap to the next line? How should spacing adjust? Pretext makes these operations near-instantaneous, even when switching between Latin and Arabic (RTL) scripts.
B2B tools routinely display tables with hundreds of rows containing names, job titles, and company names of varying lengths. Auto-sizing columns requires measuring the widest content in each column. With traditional DOM measurement, this can freeze the interface for a full second. Pretext reduces this to single-digit milliseconds.
The CRM use case extends beyond simple column sizing. Modern prospecting tools display prospect data in card views, Kanban boards, and timeline interfaces, each of which requires text measurement for different layout contexts. A contact card might need to truncate a long job title to two lines, while the same data in a table view should auto-size the column. With Pretext, these calculations happen in microseconds, enabling truly fluid transitions between view modes without layout jank.
For teams running multi-channel outreach campaigns combining cold email and LinkedIn messaging, the text measurement challenge compounds. LinkedIn messages have different character limits and display widths than email subject lines. A prospecting platform that can instantly calculate how the same message will render across both channels provides a significant competitive advantage. Pretext makes this cross-channel preview feasible without maintaining separate rendering engines for each platform.
The multilingual dimension is where Pretext delivers its most outsized value. In global B2B SaaS, localization goes beyond translating UI strings. It requires every visual component to adapt correctly to alphabets and word lengths that vary dramatically.
A button labeled 'Send' in English needs to also fit 'Envoyer' in French, 'Senden' in German, and '送信する' in Japanese without overflow or truncation. Emelia, which runs prospecting campaigns across 40+ languages (powered by translation technology from Bridgers), faces this challenge at every level of its interface.
The challenge is especially visible in multilingual data tables. A CRM displaying international contact names must simultaneously handle short English names ('John Smith') and considerably longer strings in other scripts. Thai names, for example, often include honorific prefixes that significantly extend character count. Arabic names render right-to-left and require inverted width calculations. Without Pretext, every cell in such a table requires an expensive DOM call.
Another concrete use case involves email sequence composition interfaces. When a sales team creates a campaign targeting German-speaking markets, compound German words like 'Geschäftsführungsmitglied' or 'Softwareentwicklungsabteilung' can blow out button widths and text line lengths. The ability to pre-calculate these overflows before the email is even sent represents a significant quality improvement for professional emailing platforms.
Pretext handles complex scripts natively through Intl.Segmenter: Arabic with contextual shaping and RTL rendering, CJK with thousands of distinct glyphs, Thai with tonal positioning, Devanagari with combining characters, and even composed emoji sequences. The repository's test suite includes full-length corpus validation in all of these languages, verified against actual browser rendering.
Criteria | DOM (reflow) | Canvas measureText | Pretext |
|---|---|---|---|
Speed (1,000 items) | ~94 ms | ~5 ms | ~0.05 ms |
Triggers reflow | Yes (blocking) | No | No |
Multi-line support | Yes (native) | No (single line) | Yes |
RTL/bidi support | Yes (native) | Partial | Yes (full) |
CJK support | Yes | Yes | Yes |
Server-side (SSR) | No | No (needs Canvas) | Planned (roadmap) |
Bundle size | Native | Native | ~10 kb gzipped |
Dependencies | None | None | None |
Accuracy | Pixel-perfect | Pixel-perfect | Sub-pixel (±0.5px) |
The primary tradeoff is accuracy versus speed. Pretext provides sub-pixel measurements (within half a pixel in most cases). For truncation detection, column sizing, and height estimation, this precision is more than adequate. For pixel-perfect rendering where exact sub-pixel accuracy is critical, the DOM method remains necessary.
Cheng Lou is not a newcomer to the JavaScript ecosystem. He created react-motion (21,000+ stars), the library that revolutionized React animations by replacing the duration-and-easing paradigm with physics-based springs. At Facebook, he led ReasonML, an OCaml-inspired language that powered messenger.com.
His ReactEurope 2016 talk 'On the Spectrum of Abstraction' remains a widely referenced conference talk. Pretext follows the same pattern: find a fundamental constraint everyone accepts as given, and remove it with math. The GitHub repository is MIT licensed.
Pretext's launch generated an unusually enthusiastic response from the front-end community. Within days, developers worldwide created spectacular demos: a dragon that pushes text aside in real-time, physics simulations applied to typography, and paragraph morphing effects.
Beyond individual reactions, Pretext triggered an unprecedented wave of creativity in the front-end community. The concept of 'DOM-free text layout' inspired dozens of developers to build experimental demos. A Romanian developer built an animated dragon that physically pushes text aside as it moves, with 80 articulated segments and a complete layout recalculation every frame all at 60fps with zero DOM reflows. Others created physics simulations where balls bounce between text lines, or morphing effects where paragraphs transform in real-time.
This creative explosion illustrates a fundamental point: Pretext doesn't just optimize an existing calculation. By making text measurement essentially free, the library opens up interactive design possibilities that were previously unthinkable due to browser performance constraints. Interface designers can now envision text-based animations and transitions without worrying about the browser's performance limitations.
Reactions from major JavaScript ecosystem figures speak volumes:
Guillermo Rauch (Vercel CEO): 'So good. Thank you.'
shadcn (creator of shadcn/ui): 'Incredible. Trying this.'
Rasmus Andersson (Inter font designer): 'Fantastic! What a great idea.'
Ryan Florence (Remix co-creator) immediately asked about Canvas support and shared a demo
Garry Tan (Y Combinator CEO) integrated Pretext into his own GStack tool
The interactive demos and community demos showcase creative use cases pushing the boundaries of in-browser text rendering.
Pretext has genuine limitations worth understanding before adoption:
Complex script handling (Arabic with contextual ligatures, Thai, Devanagari) is supported but may show slightly larger measurement deviations than Latin scripts
Server-side rendering (SSR) is on the roadmap but not yet available
Custom non-web fonts require upfront configuration work
The library handles measurement and layout, not final text rendering
The system-ui font fallback is not recommended on macOS for accuracy reasons
Despite these limitations, the project is actively maintained, the contributor community is growing rapidly, and the codebase follows modern JavaScript best practices with comprehensive test coverage across Thai, Chinese, Korean, Japanese, Arabic, and more.
npm install @chenglou/pretext
# or
pnpm add @chenglou/pretext
# or
bun add @chenglou/pretextIntegration is straightforward. The library has zero external dependencies and works in all modern JavaScript environments (browser, Node.js, Bun). Here's a complete example for email subject line truncation prediction:
import { prepare, layout } from '@chenglou/pretext';
// Check if an email subject line will truncate in Gmail
function checkSubjectTruncation(subject: string) {
const prepared = prepare(subject, '14px Roboto');
const result = layout(prepared, 520, 20); // 520px = Gmail desktop width
return {
willTruncate: result.lineCount > 1,
width: result.width,
suggestion: result.lineCount > 1
? 'Subject will truncate in Gmail. Consider shortening.'
: 'Subject fits perfectly in Gmail.'
};
}
// Test with English and German subjects
console.log(checkSubjectTruncation('Discover our latest prospecting features'));
console.log(checkSubjectTruncation('Entdecken Sie unsere neuesten Prospektionsfunktionen'));Pretext doesn't reinvent web development. It solves a specific problem text measurement and layout with an elegant approach and exceptional performance. But that specific problem is a silent bottleneck affecting thousands of web applications worldwide.
What makes Pretext particularly noteworthy is that it emerged from a tradition of solving problems through mathematical elegance rather than brute engineering force. Where other libraries might optimize DOM access patterns or batch reflow operations, Pretext simply removes the DOM from the equation entirely. This philosophical approach finding the right abstraction rather than optimizing the wrong one is what earned Cheng Lou his reputation in the React community, and it's what makes Pretext feel less like an incremental improvement and more like a paradigm shift.
The timing is particularly relevant. As B2B SaaS goes global and products must support dozens of languages simultaneously, the tools underpinning these interfaces must evolve accordingly. Text measurement seemed like a solved problem, but the performance gap between traditional approaches and what Pretext offers reveals just how much optimization remains possible in the most fundamental building blocks of web development.
For teams building multilingual SaaS products, visual editors, or data-intensive interfaces, Pretext deserves serious evaluation. The performance gains are real, the integration is straightforward, and the community forming around the project is an encouraging sign of its longevity.

No commitment, prices to help you increase your prospecting.
You don't need credits if you just want to send emails or do actions on LinkedIn
May use it for :
Find Emails
AI Action
Phone Finder
Verify Emails