I recently explored a JavaScript library called Pretext by chenglou that genuinely changed how I think about text in the browser. Here's the problem it solves Whenever you need to know how tall a block of text is (for virtualized lists, chat bubbles, dynamic layouts), the browser forces you to inject text into the DOM and call getBoundingClientRect() or offsetHeight. This triggers a layout reflow one of the most expensive operations in the browser. Do this for hundreds of items and your app starts to lag and jank. Pretext sidesteps this entirely. 🔹 How It Works Instead of touching the DOM, Pretext uses the Canvas measureText() API under the hood the browser's own font engine without triggering any reflow. 🔹 The Two-Phase Design prepare() — does the heavy lifting once: segments the text, applies line-breaking rules, measures widths layout() — pure arithmetic after that, no DOM, no canvas, just math 🔹 What You Get Back const { height, lineCount } = layout(prepared, 300, 24) 300 = your container width (like CSS width) 24 = your line height (like CSS line-height) height = total height Pretext calculates for you 🔹 Why This Matters Proper virtualization without guesswork Text layout on Canvas, SVG, and WebGL Supports all languages — Arabic, CJK, Emojis, mixed bidirectional text Works server-side eventually I tested it myself and got height: 24 and lineCount: 1 on the first run. Then narrowed the width and watched the lines wrap no DOM involved at all. 🔗 GitHub: https://lnkd.in/g8ZutRQB 🌐 Docs: https://pretextjs.dev/ #webdevelopment #javascript #typescript #frontend #webdeveloper #opensource

To view or add a comment, sign in

Explore content categories