⚠️ This post links to an external website. ⚠️
Most syntax highlighters work by wrapping each token (keywords, strings, operators, etc.) in individual
<span>elements with CSS classes. For a typical code snippet, this can mean creating hundreds or even thousands of DOM nodes:<span class="keyword">const</span><span class="identifier">greeting</span><span class="operator">=</span><span class="string">"Hello World"</span>Each of these nodes adds overhead to the browser’s rendering pipeline—more nodes to parse, more layout calculations, more paint operations, and more memory consumption. For documentation sites or code-heavy applications, this can significantly impact performance.
The CSS Custom Highlight API provides a way to style arbitrary text ranges without modifying the DOM structure. Instead of creating wrapper elements, you define
Rangeobjects that point to specific character positions in text nodes, group them by style type, and register them with the browser’s highlight registry.
continue reading on pavi2410.com
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.