CSS Custom Highlight API
This library leverages the modern CSS Custom Highlight API to provide non-invasive text highlighting
capabilities. Unlike traditional approaches that wrap text in HTML elements like <mark>
or <span>, the CSS Custom Highlight API allows you to style arbitrary text ranges
without mutating the DOM structure. This means your original HTML remains untouched, making it perfect
for highlighting search results, annotations, or any dynamic text selection without interfering with
your existing markup or event handlers. The API uses the ::highlight() pseudo-element
combined with JavaScript Range objects to create highlights that are rendered by the browser's
compositing engine, resulting in excellent performance even with thousands of highlights.
Framework-Agnostic Design
One of the key strengths of this library is its framework-agnostic architecture. The core highlighting
logic is written in pure TypeScript and uses only standard browser APIs like TreeWalker, Range, and
CSS.highlights. This means you can use it with any JavaScript framework—Vue, Svelte, Angular, or even
plain vanilla JavaScript—without any framework-specific dependencies. The vanilla JavaScript API
provides a simple, imperative interface through the createHighlight() function, which
returns a controller object for managing highlights. This design philosophy ensures that the library
remains lightweight, performant, and easy to integrate into any project, regardless of your technology
stack. Whether you're building a complex single-page application or a simple static website, this
library fits seamlessly into your workflow.
Performance and Efficiency
Performance is a critical consideration when implementing text highlighting, especially when dealing with large documents or frequent updates. This library addresses these challenges through several optimizations. The TreeWalker API is used for efficient DOM traversal, allowing the library to process only text nodes while automatically skipping script tags, style elements, and other non-content nodes. Regex patterns are pre-compiled once per search term, avoiding repeated compilation overhead. The library also implements configurable limits on the maximum number of highlights to prevent performance degradation, and includes built-in debouncing support for scenarios where search terms change frequently, such as real-time search interfaces. These optimizations ensure that highlighting remains fast and responsive even when processing thousands of matches across complex document structures, making it suitable for use in production applications where performance matters.