Search

Syntax Highlighting with no spans?!

When I think of showing off syntax highlighted code on the web, I think of code that takes in a string of code, finds relevant substrings (tokens) with elaborate RegExes, then wraps them in <span>s with classes to that color can be applied to those classes. This is quite literally how it works. The really nice syntax highlighter Prism has all sorts of RegExes to find the right stuff. I think if you poked around other syntax highlighting tools for the web you’d find largely the same approach.

BUT THERE IS ANOTHER WAY. Bramus digs into it nicely here.

Brass tacks, there is a Highlight() API in JavaScript, where you can set a Range() on text, then give it a name. Then in CSS, you can select that highlight with ::highlight(name) and colorize it. This is useful for simple use cases like building on-page search yourself, but is everything you need for even something as elaborate as syntax highlighting.

I would have guessed this would be a real boon for performance, with so much less HTML required and really no DOM manipulation at all. But as Bramus points out, the performance actually have some problems. Would be nice to see some actual benchmarks. There are variety of other downsides too, like being quite limited in styling (like ::selection) and not having pointer events to do things like hover styles or positioned popups.

To me it seems like the biggest downside is that you could never do this server-side, which is almost certainly a performance win, whereas you can do the make-a-bunch-of-spans style highlighting server-side.

It's time to take your JavaScript to the next level

Frontend Masters logo

Frontend Masters is the best place on the web to really learn JavaScript. We have a complete learning path from the biggest and best teachers in JavaScript to help you make the most out of the web's biggest language.

Leave a Reply

Your email address will not be published. Required fields are marked *

Frontend Masters ❤️ Open Source

Did you know? Frontend Masters Donates to open source projects. $313,806 contributed to date.