javascriptparsingmarkdownremarkjs

How can I parse markdown asynchronously using unified and remark-parse?


I want to parse markdown in the browser and do that ansyc, so nothing "hangs". However, the unified parse function is only synchronous. So, how to parse Markdown without blocking the browser/UI?

My code:

import { unified } from "unified";
import remarkParse from "remark-parse";

const tree = unified().use(remarkParse).parse(markdown);

Solution

  • For non-blocking browser scripts you could take a look at Service Workers. See the docs for details. With workers, there will no (or close-to) changes in the code. It you need to pass information between the primary page and the worker you need to pass so-called messages between each of them (postMessage/onmessage, see examples on the mentioned docs page).

    tl;dr: Web Workers are background threads for js code that's running aside of the default js cycle of the tab (also possible if the tab is closed).