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
More Relevant Posts
-
🚀 What is JavaScript? Think of it as Your Personal Website Butler 🤔 Imagine you're at a hotel, and you want to request a wake-up call or extra towels. You can't just walk into the staff room and tell them yourself. Instead, you give your request to the butler, who then communicates it to the right person. In web development, JavaScript acts like that butler. It's a programming language that helps your website interact with users, making it dynamic and engaging. When you click a button, fill out a form, or scroll through a page, JavaScript is working behind the scenes to make that happen. For example, let's say you have a website with a button that says "Click me!" When you click that button, JavaScript can make it change color, display a message, or even load new content without needing to reload the entire page. Here's a simple example: ```javascript button id="myButton" Click me! /button script document.getElementById, "myButton", .addEventListener, "click", function, , alert, "You clicked the button!", ; , ; /script ``` In this code, JavaScript listens for a click event on the button and then displays an alert message. Did this help? Save it for later. ✅ Check if your website uses JavaScript to create a better user experience. #WebDevelopment #LearnToCode #JavaScript #CodingTips #TechEducation #WebDesign #FrontendDevelopment #JavaScriptSimplified #WebButler #DynamicWebsites #UserExperience
To view or add a comment, sign in
-
Have you seen Pretext? Holy smokes, it's awesome. Pretext is a brand-new JavaScript/TypeScript library for multiline text measurement & layout by Cheng Lou, previously a React core developer and the original creator of the react-motion animation library. It lets you calculate the height of line-wrapped text without ever touching the DOM. Until now these kinds of UI operations required rendering the text and measuring the result, which is a super expensive operation. For us this matters because Research Tool has some hard UI challenges. We treat a large corpus as a navigable system, preserve document structure, and treat diff as a discovery primitive, so the interface has to present long passages, side-by-side comparisons, and anchored evidence. With Pretext we can now do all that without hot-path DOM measurements and layout reflow. It's got two super-useful modes: fast paragraph-height prediction and manual line layout. This means we can drive virtualized chat, masonry and occlusion using predicted text height, rich inline text, and custom line routing. Wanted to do my part to spread the word. Check it out https://lnkd.in/ggN9YxFP
To view or add a comment, sign in
-
💻 Ever wondered how your HTML actually renders in a browser? As developers, we write HTML, CSS, and JavaScript daily… But what really happens behind the scenes when you open a webpage? Let’s break it down 👇 🔹 1. Browser Reads HTML The browser loads your .html file and starts parsing it line by line. 🔹 2. DOM Creation HTML is converted into a structured tree called the DOM (Document Object Model) — this is what JavaScript interacts with. 🔹 3. CSS Parsing All styles are processed and converted into a CSSOM (CSS Object Model). 🔹 4. Render Tree Formation DOM + CSSOM = Render Tree This defines what will actually appear on the screen. 🔹 5. Layout Calculation The browser calculates size and position of every element. 🔹 6. Painting Pixels are drawn on the screen — your UI becomes visible 🎨 🔹 7. JavaScript Execution The browser’s JavaScript engine (like V8) executes code and can dynamically modify the DOM. 🔄 Any DOM change triggers reflow & repaint — impacting performance. 🧠 Key Insight: HTML is not “executed” — it is parsed and transformed into a structure that the browser understands and renders. ⚡ Why this matters: Helps optimize performance Avoid unnecessary DOM updates Write better frontend code Understanding this flow changed how I think about frontend performance and debugging. What part of the rendering process surprised you the most? #WebDevelopment #JavaScript #Frontend #HTML #CSS #BrowserInternals #SoftwareEngineering
To view or add a comment, sign in
-
Pretext a new JavaScript library just flipped how web apps have measured text for decades. Every web app has done it the same way: inject text into a hidden DOM element, read offsetHeight, throw it away. Simple enough until content starts arriving token by token. With LLM powered chat interfaces now everywhere, this is a problem the entire industry is quietly hitting. Text streams in continuously, the UI needs to know how tall each message is in real time for scroll anchoring, layout stability, keeping the interface from jumping as responses grow. Each offsetHeight call triggers layout reflow. On mobile that's 10-30ms per read. At streaming speed, across multiple concurrent message threads, you debounce, approximate, cache. It holds. But you're negotiating with the browser, not working with it. Pretext's premise: text measurement doesn't need the DOM. It's arithmetic. If you know the rendered width of each word, you walk the text, track a running total, and insert a line break when it exceeds the container width. Height is lines x line height. The browser does this internally during reflow. Pretext does it in userland, without the rest of the machinery. Two functions: prepare() measures each word segment once using Canvas measureText() and caches the results. A one-time cost of ~0.1ms per font configuration. layout() pure arithmetic over cached widths. Returns exact height and line count. ~0.0002ms per call hundreds of times faster than DOM measurement. No reflow. Zero DOM access. One prepare() per font config. Then layout() at any container width mobile, tablet, desktop with just arithmetic. On resize: skip prepare(), only rerun layout(). What this unlocks: • Streaming interfaces exact heights on every token. Pixel perfect scroll anchoring from character one. • Virtual scrolling measure all row heights before mounting a single DOM element. • Server-side layout Node.js has no DOM, but it runs Pretext. Pre-compute heights on the server, eliminate layout shift on first load entirely. It's not a workaround, it's a different model. Pretext is built by Cheng Lou — ex-React core team at Facebook, creator of react-motion. MIT licensed. 15KB. Zero dependencies. Framework agnostic. 35k+ GitHub stars. If you've ever approximated text height and accepted the jank as the cost of doing business this is worth a look. See what zero DOM text layout looks like in practice https://lnkd.in/d38_Gbd7 #FrontendArchitecture #WebPerformance #ReactJS #JavaScript #SystemDesign #FullStack
To view or add a comment, sign in
-
Build a smart Table of Contents 📖 (Zero JavaScript needed): Making a Table of Contents used to be a pain. You had to write a lot of JavaScript. You had to track the screen to see where the user was reading. It was a lot of hard work. Not anymore. Now, CSS can track it for you. The Setup First, you just need a normal list of links in your HTML. HTML <ol class="list"> <li><a href="#getting-started">Getting Started</a></li> <li><a href="#core-concepts">Core Concepts</a></li> </ol> The Magic Trick Here is the secret CSS. We use two brand new tools to make it work. CSS /* 1. Tell the list to watch the scroll */ .list { scroll-target-group: auto; } /* 2. Highlight the active link */ .toc-list a:target-current { color: blue; font-weight: bold; background: lightblue; } How this works: scroll-target-group: This turns your list into a smart tracker. It watches the page for you. :target-current: This finds the exact link that matches the part of the page you are reading right now. When you scroll down, the blue highlight moves down the list all by itself! A quick warning: This is a brand new CSS tool. Right now, it only works on Chromium browsers (like Google Chrome and Microsoft Edge). It is not ready for all users yet. But keep an eye on it! Soon, we will never need JavaScript for this again. Anyways, CSS is evolving fast. But while these features are cool, layouts are still where most devs struggle. One design, 25 screen sizes… feels like throw and pray. Flexbox and Grid fix that. I wrote a 112-page visual guide that shows you how to build any layout in an afternoon. Grab it here: [ https://lnkd.in/dZmwzdcc ]
To view or add a comment, sign in
-
-
Every frontend dev has written this exact JavaScript to auto-resize a textarea. Now CSS does it in one line. 👇 You set height to auto. Then you set it to scrollHeight. Then you add overflow: hidden. Then you wonder why you're doing DOM math just to make a text box grow. CSS 2025 ships field-sizing: content — one property, zero JavaScript, native browser performance. ❌ JavaScript approach Listen to the input event, reset height to auto, then set it to scrollHeight. Every dev has copy-pasted this snippet at least once — it's boilerplate that simply shouldn't exist. ✅ CSS field-sizing: content One CSS property. The browser handles the resize natively. Works on textarea and input elements. No event listeners, no layout thrashing, no JS bundle weight. It works on textarea AND input elements. The element grows with its content automatically, shrinks when you delete, and you don't touch a single event listener. No more copy-pasting that resize snippet from Stack Overflow. No more layout thrashing on every keystroke. This is what CSS was always supposed to do. One property replaces 7 lines of JavaScript. Ship less, style more. Golden Rule: If you're firing a JS event just to measure and set an element's own size — CSS probably has a native answer now. Check before you script. #CSS #WebDevelopment #Frontend #JavaScript #CleanCode #JS #FrontendDeveloper #SoftwareEngineer #100DaysOfCode #WebDesign #CSSDesign #TechTips #Developer #LearnToCode #UIDesign #NewCSS
To view or add a comment, sign in
-
-
🚀 Ever wondered how to dynamically create elements in JavaScript? Let's dive in! 🤓✨ Creating elements dynamically allows developers to generate content on-the-fly, enhancing user experience and interactivity on websites. It's a powerful technique for adding, updating, or removing elements based on user actions or data changes. ⭐️ Why it matters: Dynamic element creation gives developers the flexibility to build responsive and interactive web applications tailored to user needs, leading to a more engaging and personalized user experience. Plus, it optimizes performance by only adding elements when necessary. Here's a simple breakdown: 1️⃣ Create an element using document.createElement() 2️⃣ Set attributes and content for the element 3️⃣ Insert the element into the DOM using appendChild() ```javascript // Create a new paragraph element const newPara = document.createElement('p'); // Add text content newPara.textContent = 'Dynamic content created!'; // Append the element to an existing container document.getElementById('container').appendChild(newPara); ``` Pro tip: Utilize event listeners to dynamically respond to user interactions and update the content accordingly. 🎯 Common mistake alert: Forgetting to reference the container to append the newly created element can result in elements not displaying as intended. Double-check your target container! 🤔 What's the most creative way you've used dynamic element creation in your projects? Share below! Let's inspire each other. 💡🌟 🌐 View my full portfolio and more dev resources at tharindunipun.lk #JavaScript #WebDevelopment #DynamicElements #CodeNewbie #DeveloperTips #FrontendDevelopment #InteractiveWebsites #WebDevProjects #LearnToCode
To view or add a comment, sign in
-
-
🚀 Built a Simple Calculator using HTML, CSS & JavaScript! Today I worked on a beginner-friendly project — a fully functional Calculator 💻✨ 🔧 Tech Stack: • HTML – Structure • CSS – Styling & UI • JavaScript – Logic & Functionality 💡 Features I implemented: ✔️ Basic arithmetic operations (+, −, ×, ÷) ✔️ Clear (AC) and Delete (DEL) functions ✔️ Responsive button-based input ✔️ Clean and modern UI design ⚡ What I learned: • Handling DOM elements using JavaScript • Using event listeners effectively • Managing user input dynamically • Debugging small but tricky errors (like class name mismatches & syntax issues 😅) This project helped me strengthen my fundamentals and confidence in frontend development. 📌 Next Step: I’m planning to improve this by adding keyboard support and better error handling! #WebDevelopment #JavaScript #HTML #CSS #BeginnerProject #CodingJourney #FrontendDevelopment #BCA #LearningByDoing
To view or add a comment, sign in
-
Automatic Semicolon Insertion (ASI) in JavaScript ? Automatic Semicolon Insertion (ASI) in JavaScript is a feature where the JavaScript engine (in browsers or environments like Node.js) automatically inserts semicolons (;) in your code when you omit them—based on specific parsing rules. 🔹 Why ASI exists JavaScript was designed to be forgiving, so you can write code without always adding semicolons manually: let a = 5 let b = 10 console.log(a + b) The engine interprets it as: let a = 5; let b = 10; console.log(a + b); 🔹 When ASI inserts semicolons ASI happens mainly in these situations: 1. At line breaks (if needed to avoid syntax errors) let x = 5 let y = 10 ✔ Semicolons inserted automatically. 2. Before a closing brace } function test() { return 5 } ✔ Interpreted as: function test() { return 5; } ✅ Best Practices Always use semicolons (;) for consistency Or follow a strict style guide like Airbnb JavaScript Style Guide Be extra careful with: return lines starting with (, [, +, -, / 🔹 Then why does it look different in browser console vs VS Code? Because they do different jobs: 🟢 Browser Console Runs your code immediately using the engine (like V8) You don’t see semicolons, but internally ASI is applied during parsing 🟡 VS Code Just an editor (Visual Studio Code) It does NOT insert semicolons by itself But extensions/tools can modify your code visually: Examples: Prettier → can automatically add semicolons ESLint → can enforce semicolon rules 👉 If you see semicolons being added in VS Code, it's likely one of these tools—not ASI. Test your JavaScript fundamentals with output-based interview questions focused on scope, hoisting, closures, and asynchronous behavior. 💬 Share your answer or reasoning in the comments. #JavaScript #InterviewPreparation #SoftwareEngineering #WebDevelopment #DevelopersOfLinkedIn #frontend #backend #coding #learning
To view or add a comment, sign in
-
🔍 JavaScript Concept You Might Have Heard (First-Class Functions/Citizens) You write this: function greet() { return "Hello"; } const sayHi = greet; console.log(sayHi()); // ? 👉 Output: Hello Wait… 👉 We assigned a function to a variable? 👉 And it still works? Now look at this 👇 function greet() { return "Hello"; } function execute(fn) { return fn(); } console.log(execute(greet)); // ? 👉 Passing function as argument? 👉 And calling it later? This is why JavaScript functions are called First-Class Functions 📌 What does that mean? 👉 Functions are treated like any other value 📌 What can you do with them? ✔ Assign to variables ✔ Pass as arguments ✔ Return from another function ✔ Store inside objects/arrays Example 👇 function outer() { return function () { return "Inside function"; }; } console.log(outer()()); // ? 👉 Function returning another function 📌 Why do we need this? 👉 This is the foundation of: ✔ Callbacks ✔ Closures ✔ Functional programming ✔ Event handling 💡 Takeaway: ✔ Functions are just values in JavaScript ✔ You can pass them, store them, return them ✔ That’s why they are “first-class citizens” 👉 If you understand this, you understand half of JavaScript 🔁 Save this for later 💬 Comment “function” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development