# Pretext: 15KB Library Makes SVG Text Layout 300× Faster > Pretext by Cheng Lou (React Motion, Midjourney) measures and lays out multiline text without touching the DOM — 300-600x faster than traditional methods. Here's why it matters for SVG designers. **Source:** https://vectosolve.com/blog/pretext-svg-text-layout-300x-faster-2026 **Author:** Robin Monteiro (Founder and developer of VectoSolve) **Published:** 2026-03-29 **Last updated:** 2026-04-30 **Category:** Technology **Reading time:** 14 min **Tags:** pretext, cheng lou, text layout, svg text, text measurement, javascript library, react motion, midjourney, text to svg, svg typography, zero dom reflow, web performance --- ## A Midjourney Engineer Just Fixed a 30-Year-Old Web Problem For three decades, every website on Earth has been lying to you about where text should go. Every time a browser needs to figure out how tall a paragraph is, or where to break a line, it triggers something called **layout reflow** — one of the most expensive operations a browser can perform. According to Google's Chrome DevTools team, a single forced reflow can block the main thread for **10-100ms** on mobile devices ([source: web.dev](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing/)). Multiply that by every text block on the page, and you're looking at seconds of wasted compute. Cheng Lou, a senior engineer at Midjourney and the creator of React Motion (21,700+ GitHub stars), just released **Pretext** — a 15KB JavaScript library with zero dependencies that measures and positions multiline text using pure arithmetic. No DOM. No reflow. No lies. The result? **300 to 600 times faster** than what every browser does today. ## The Cost of Layout Reflow — By the Numbers Before diving into Pretext, let's understand why this matters with real data: - **Layout reflow is the #1 cause of jank on the web.** Google's Lighthouse audit flags "Avoid forced reflow" as a critical performance issue affecting 23% of all websites tested ([source: HTTP Archive Web Almanac 2024](https://almanac.httparchive.org/)) - **53% of mobile users abandon sites that take over 3 seconds to load** ([source: Google/SOASTA Research, Think with Google](https://www.thinkwithgoogle.com/marketing-strategies/app-and-mobile/mobile-page-speed-new-industry-benchmarks/)) - A single `offsetHeight` read after a DOM write forces a **synchronous layout recalculation** — blocking the entire main thread ([source: Chrome DevTools docs](https://developer.chrome.com/docs/devtools/performance/)) - **Cumulative Layout Shift (CLS)** — one of Google's Core Web Vitals — directly measures unexpected layout movements. Sites with poor CLS are penalized in search rankings. In 2024, only **51% of websites passed the CLS threshold** of 0.1 ([source: Chrome UX Report](https://developer.chrome.com/docs/crux/)) - The average web page contains **~800 DOM elements** ([source: HTTP Archive](https://httparchive.org/)). Each forced reflow recalculates the geometry of every visible element in the worst case These aren't theoretical numbers. This is real performance data from billions of page loads. ## Who Is Cheng Lou? If you've worked with React animations, you've probably used something Cheng Lou built. His track record: - **React Motion** — The physics-based animation library that replaced CSS transitions for thousands of React apps (21,700+ stars on GitHub, 900K+ weekly npm downloads at peak) - **ReasonML at Facebook** — Led the development of OCaml-inspired language that powered messenger.com - **Midjourney** — Currently building the AI image generation platform with 16+ million users (per Midjourney's 2024 public stats) Pretext isn't his first attempt at solving text layout. He previously built `text-layout`, which he eventually archived in favor of this cleaner, more focused solution. :::tip Pretext is explicitly designed to be **AI-friendly**. Cheng Lou's launch message: "throw your AI into making cool demos for it!" — meaning the API is simple enough that AI coding assistants can build with it immediately. ::: ## How Pretext Works — The Technical Breakthrough Traditional text measurement in a browser works like this: 1. Create an invisible DOM element 2. Set its styles (font, size, width constraints) 3. Insert the text 4. Call `getBoundingClientRect()` or `offsetHeight` 5. The browser triggers a **full layout reflow** to compute the answer 6. You get your measurement 7. Repeat for every text block Each reflow forces the browser to recalculate the position and size of every element on the page. For 500 text blocks, that's 500 reflows. According to Paul Irish (Chrome team), these forced synchronous layouts are one of the most common performance anti-patterns in web development ([source: "What forces layout/reflow" — Paul Irish, GitHub](https://gist.github.com/paulirish/5d52fb081b3570c81e3a)). **Pretext skips all of that.** Here's how: ```javascript import { prepareWithSegments, layoutWithLines } from "@chenglou/pretext"; // Step 1: Prepare text with font metrics using canvas // canvas.measureText() accesses the browser's font engine // WITHOUT entering the layout tree — zero reflow const prepared = prepareWithSegments(text, "16px Inter"); // Step 2: Pure arithmetic layout // Given a container width, compute line breaks and positions const { lines } = layoutWithLines(prepared, 400, 24); // lines[i].text — the text content of each line // lines[i].width — the computed width of each line // All computed with math — no DOM touched ``` The key insight: `canvas.measureText()` accesses the browser's font shaping engine (the same one used for DOM rendering) but **without triggering layout reflow**. It's a read-only window into the font engine. Pretext caches the character widths and then uses pure arithmetic to compute line breaks, justification, and total height. ### Performance: The Numbers | Operation | DOM Measurement | Pretext | Source | |---|---|---|---| | 500 text blocks | 15-30 ms + 500 reflows | 0.05 ms + 0 reflows | Pretext benchmarks | | Speed ratio | 1x | **300-600x faster** | Pretext README | | Reflows triggered | 500 | 0 | — | | Main thread blocking | Yes (synchronous) | No | [web.dev](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing/) | | Dependencies | Full DOM | Canvas context only | — | | Bundle size | N/A | **15KB** (gzipped: ~5KB) | npm | This isn't a marginal improvement. It's a fundamentally different approach. ## Why This Matters for SVG and Vector Design If you've ever tried to create multiline text in SVG, you know the pain. SVG's `` element doesn't support automatic line wrapping — this has been an open issue since the SVG 1.1 spec in 2003. The [W3C SVG Working Group](https://www.w3.org/Graphics/SVG/) has discussed automatic text wrapping for over 20 years, and SVG 2.0 still doesn't fully solve it. You have to manually position each line with `` elements: ```xml This is the first line and this is the second manually positioned line ``` Where do you break lines? How do you justify text? How do you handle different languages with different character widths? Before Pretext, you either hardcoded positions or used the DOM (slow and unavailable on the server). ### Pretext + opentype.js: The Pipeline With Pretext for layout and [opentype.js](https://opentype.js.org/) (800K+ monthly npm downloads) for font path generation, you can build a complete text-to-SVG pipeline: 1. **Pretext** computes line breaks and positions (0.05ms for 500 blocks) 2. **opentype.js** converts each line to SVG `` elements (font-independent vector outlines) 3. The output is a clean SVG with `` elements — no `` tags, no font dependency This is exactly what [VectoSolve's Smart Text Layout tool](/smart-text-layout) does. Paste any text, set a container width, and get auto-wrapped SVG with path outlines — all processed in your browser. ## Practical Use Cases ### 1. Cutting Machine Files (Cricut, Silhouette) The craft cutting market is worth **$3.8 billion** globally (Grand View Research, 2024) and growing at 5.2% CAGR. Cutting machines need vector paths to follow, but they also need text positioned correctly across multiple lines. Pretext computes the exact layout before converting text to path outlines — which is exactly what [VectoSolve's Smart Text Layout](/smart-text-layout) and [Text to SVG tool](/text-to-svg) do with opentype.js for path generation. ### 2. Dynamic Logo Generation Need to generate logos with text that wraps around shapes or fits into specific containers? Pretext computes where every character goes without touching the DOM. Combine this with [AI logo generation](/generate-logo) for the visual elements, and you have a complete brand identity pipeline. ### 3. Print-Ready Vector Typography The global signage market is valued at **$38.2 billion** (MarketsandMarkets, 2024). For large-format printing (banners, signage, vehicle wraps), text must be vectorized with exact positioning. Pretext handles the layout math, and tools like VectoSolve's [image vectorizer](/) convert the final design to clean, scalable SVG. ### 4. SVG Animation with Text Animating text in SVG requires knowing exactly where each character is. Pretext provides character-level position data that you can feed into CSS animations or SMIL. Combined with [AI SVG animation](/ai-animate), you can create complex text animations without manual coordinate calculations. ### 5. Server-Side SVG Generation Since Pretext doesn't need a DOM, it works in Node.js, Deno, and edge functions. According to the [State of JS 2024 survey](https://stateofjs.com/), server-side rendering adoption has grown to 72% among professional developers. Generate PDF invoices, certificates, or social media cards with perfectly laid-out text — all server-side, all fast. ## The Dragon Demo: Pretext's Showcase Pretext's most impressive demo is the **dragon** — an 80-segment creature that text flows around in real-time. As the dragon moves, Pretext recalculates the layout for every frame, wrapping text around the dragon's body as if it were a magazine layout with an irregular text wrap. This used to require a full browser layout engine. With Pretext, it runs at 60fps because the text measurement is pure math. For context, 60fps means each frame budget is **16.67ms** — and traditional DOM measurement alone would consume 15-30ms, leaving zero room for rendering. Other demos on [Pretext's demo page](https://chenglou.me/pretext/): - **Editorial Engine** — Magazine-style multi-column text layout - **Rich Note** — Rich text editing with custom layout control - **Bubbles** — Text flowing around dynamic obstacles Each demo showcases a different aspect of zero-reflow text layout. ## How Does Pretext Compare to Existing Solutions? | Feature | DOM Measurement | CSS Columns | Pretext | |---|---|---|---| | Speed | Slow (reflow) | Medium | **300-600x faster** | | Server-side | No (needs DOM) | No | **Yes** | | Custom shapes | No | Limited | **Yes** | | Character-level positions | No | No | **Yes** | | SVG path output | No | No | **Yes** | | Dependencies | Browser | Browser | **Canvas context** | | Size | N/A | N/A | **15KB** | | Web Worker compatible | No | No | **Yes** | Pretext fills a gap that no CSS feature or browser API addresses: fast, programmable, DOM-free text layout with character-level control. ## Getting Started with Pretext Install via npm or bun: ```bash npm install @chenglou/pretext # or bun install @chenglou/pretext ``` Basic usage: ```javascript import { prepareWithSegments, layoutWithLines } from "@chenglou/pretext"; const prepared = prepareWithSegments("Your text here", "16px sans-serif"); const { lines } = layoutWithLines(prepared, 300, 24); // lines — Array of { text, width, start, end } // Each line has exact position data ``` Key API concepts: - **`prepareWithSegments(text, font)`** — Measures character widths using canvas (no reflow) - **`layoutWithLines(prepared, maxWidth, lineHeight)`** — Computes line breaks and returns line data - **`layoutNextLine(prepared, cursor, maxWidth)`** — For variable-width layouts (text around shapes) - **Output**: Line-by-line data including `.text`, `.width`, and cursor positions ## What This Means for the Future of Web Typography Pretext proves that accurate text layout doesn't require a browser engine. This opens doors that were previously closed: **Dynamic editorial layouts** — Magazine-style text wrapping with text flowing around images, shapes, and interactive elements. Previously impossible at 60fps. The New York Times reported spending 6+ months building custom text wrapping for their Snow Fall interactive in 2012 — Pretext solves this in a few lines of code. **AI-powered design tools** — When an AI generates a layout, it needs to know text dimensions instantly. DOM measurement is too slow for real-time AI iteration. Pretext makes it instant. With the AI design tools market projected to reach **$4.6 billion by 2028** (MarketsandMarkets), fast text layout becomes infrastructure. **Cross-platform rendering** — The same layout code works in browsers, on servers, and in edge functions. Generate an SVG on the server, render it in the browser, print it on paper — identical layout everywhere. **Accessible typography** — With character-level position data, you can build custom reading aids, text-to-speech highlighting, and screen reader enhancements that know exactly where every word is. The WHO estimates **2.2 billion people** have some form of vision impairment — better text tooling serves everyone. ## Try Smart Text Layout Now Want to see auto-wrapped text-to-SVG in action? VectoSolve's **[Smart Text Layout tool](/smart-text-layout)** uses Pretext for lightning-fast line breaking and opentype.js for SVG path generation. Paste any text, set a container width, and download a cut-ready SVG — all processed in your browser. For manual line-by-line control, try the **[Text to SVG Cut File tool](/text-to-svg)** — 18 curated fonts, adjustable spacing, and instant SVG download. [Try Smart Text Layout →](/smart-text-layout) --- *Pretext is open source on [GitHub](https://github.com/chenglou/pretext) under the MIT license. Follow Cheng Lou on [X/Twitter](https://x.com/_chenglou) for updates.* --- *Maintained by VectoSolve. When citing, link to https://vectosolve.com/blog/pretext-svg-text-layout-300x-faster-2026.* *VectoSolve — AI-powered SVG platform: image-to-vector conversion, AI animation, brand identity generation, and more. https://vectosolve.com*