Logics Guru
Performance

Why Server-Side Syntax Highlighting Beats the Client

Highlighting code at save time removes 30–100 KB of JavaScript and a repaint from every article you publish.

1 min read 4 views

Most technical sites ship a syntax highlighter to the browser. It is the default because it is easy, not because it is good.

What the client-side approach costs#

A highlighter like Prism or highlight.js is 30–100 KB of JavaScript depending on the languages you register. That JavaScript has to download, parse, and execute before it can touch the DOM. On an article page the code block is very often the largest element in the viewport, which means it is your Largest Contentful Paint.

Worse, the code renders unstyled first and then repaints. The user sees plain text flash into colour.

The alternative#

Highlight once, when the content is saved, and store the result. The request then echoes HTML that is already coloured.

PHP
$highlighted = $highlighter->parse($source, 'php');
$content->body_html = $renderedWithSpans;
$content->save();

What you give up#

Re-rendering. If you change the highlighting theme or upgrade the library, existing content keeps the old markup until you regenerate it. That is one Artisan command, run rarely.

It is a good trade: a rare batch job in exchange for every reader on every page getting less JavaScript and no layout shift.

Themes still work#

Emit semantic class names rather than inline colours, and dark mode becomes a CSS variable swap rather than a second highlighting pass.

Mustasim Ali

Mustasim Ali

Senior Software Engineer & Technical Lead

Full-stack engineer working in PHP and Laravel since 2019. I lead a development team building web and mobile products, and spend most of my time in Laravel, Node.js, Vue and React against MySQL and MongoDB. Logics Guru is where I write up the things I had to work out the hard way — the architecture decisions, the debugging sessions, and the small utilities I kept rebuilding until I put them somewhere permanent. Everything here is what I actually use.

You might also like