Zenn Tech Blog

iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚀

Accelerating Zenn Previews by Running Markdown Conversion in the Browser

に公開

The editor on the article editing page, currently provided as the "New Editor", allows you to check previews in real-time with a two-column layout. However, because the preview generation was performed on the server side, there was a certain amount of lag before edits were reflected.

To address this, we changed zenn-markdown-html, which handles preview generation (Markdown to HTML conversion), to run in the browser, achieving faster preview updates.

A while ago, I saw conversion at 60fps and was inspired to make Zenn's editor even faster.

wasm execution restrictions due to CSP (Content Security Policy)

zenn-markdown-html uses Shiki as its syntax highlighter, and Shiki standardly uses wasm (WebAssembly) for the Oniguruma regex engine.

However, since Zenn is a service that handles user-generated content, we have implemented CSP to mitigate security risks. As a result, the execution of Oniguruma's wasm was restricted, making it impossible to run Shiki in the browser.

https://zenn.dev/team_zenn/articles/introduced-csp-to-zenn

To solve this, we bypassed the CSP restrictions by switching to the JavaScript version of the regex engine provided by Shiki when running in the browser. According to the documentation, it currently has full compatibility across all languages.

https://github.com/zenn-dev/zenn-editor/pull/628

Benchmark

To verify the conversion speed in the browser, I conducted a simple benchmark. Since it runs in the browser, performance depends on the machine's specs.

Specs: Apple M4 / 32 GB

For the benchmark, I prepared three patterns of Markdown and took the average of 100 conversions each.

Case Description Character Count Avg Processing Time Output HTML Length
Small-scale Heading + Paragraph + List 91 5.42 ms 1,118
Medium-scale General article with multiple code blocks 1,578 6.25 ms 12,328
Large-scale Code blocks in multiple languages + Long text 5,110 14.39 ms 37,267

As you can see, even relatively large articles can be converted in about 15ms.

I also tested it with one of my actual large articles (which has 15 code blocks), and it was converted in 30–40ms.

File Name Character Count Avg Processing Time Output HTML Length
zenn-markdown-editor-by-cm6.md 16,858 34.14 ms 76,360

Improvement Effects

Previously, a 300ms debounce time was set to reduce server load, which gave the preview reflection a slightly sluggish feel. However, by changing the mechanism to execute processing on the browser side, the load constraints were removed, and the debounce time was reduced to 50ms.

As a result, previews are now reflected in 60–70ms, providing a smoother and more comfortable writing experience than before.

See you next time!

GitHubで編集を提案
Zenn Tech Blog
Zenn Tech Blog

Discussion