Home Solution to mermaid not render in jekyll
Post
Cancel

Solution to mermaid not render in jekyll

Mermaid在jekyll生成的页面中不渲染的问题解决方法


背景

Mermaid本身不被Github Pages支持,需要用插件或手动加入javascript脚本来支持。

问题

mermaid官方文档的getting-started页面说明来看, 将mermaid.min.js脚本加载进页面后使用mermaid.initialize(config)方法就可以开启渲染mermaid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html lang="en">
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <pre class="mermaid">
            graph LR
            A --- B
            B-->C[fa:fa-ban forbidden]
            B-->D(fa:fa-spinner);
    </pre>
    <pre class="mermaid">
            graph TD
            A[Client] --> B[Load Balancer]
            B --> C[Server1]
            B --> D[Server2]
    </pre>
    <script type="module">
      import mermaid from 'The/Path/In/Your/Package/mermaid.esm.mjs';
      mermaid.initialize({ startOnLoad: true });
    </script>
  </body>
</html>

本代码使用Github Pages生成发布网页,在chromesafari浏览器上,只有当清空缓存第一次打开的时候可以渲染mermaid图象,后续打开只会显示代码。

解决方法

无意中看到jekyllmode-toogle.html代码中的updateMermaid()方法,当显示模式变化后,会改变confg再次使用mermaid.initialize(config)方法,后面紧根mermaid.init()方法刷新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
updateMermaid() {
    if (typeof mermaid !== "undefined") {
        let expectedTheme = (this.modeStatus === ModeToggle.DARK_MODE? "dark" : "default");
        let config = { theme: expectedTheme };

        /* re-render the SVG › <https://github.com/mermaid-js/mermaid/issues/311#issuecomment-332557344> */
        $(".mermaid").each(function() {
                let svgCode = $(this).prev().children().html();
                $(this).removeAttr("data-processed");
                $(this).html(svgCode);
                });

        mermaid.initialize(config);
        mermaid.init(undefined, ".mermaid"); // **刷新渲染mermaid一次**
    }
}

于是把mermaid.init(undefined, ".mermaid");这句代码加到初始化代码的mermaid.initialize(config)后,测试每次都成功渲染mermaid

虽然问题解决,但原因未明,究其原因可能是浏览器在有缓存的情况下调用mermaid.initialize(config)时并没有真正去渲染。

This post is licensed under CC BY 4.0 by the author.

Dupidog's smart home network topology

Dripdog's 10th birthday