Adding conditional Chart.js and Mermaid charts to Chirpy
Add built-in Mermaid xychart-beta and conditional Chart.js 4 rendering to Jekyll Chirpy v7.6 with live dark mode sync and static JSON QA validation.
Plain Markdown tables rarely make latency spikes or bundle size drops stand out at a glance. This post shows how I added both built-in Mermaid
xychart-betacharts and a conditional Chart.js 4 renderer to Jekyll Chirpy v7.6—without overriding theme layouts—complete with live dark mode sync and static JSON QA checks.
Tested with Jekyll 4.4, jekyll-theme-chirpy 7.6.0, Mermaid 11 (built-in), and Chart.js 4.
Three ways to render charts in a Markdown blog
When you want numeric charts in a Jekyll post, you usually pick between static images (PNG/WebP), built-in Mermaid xychart-beta, and an interactive JS library like Chart.js. Loading a charting library globally on every page adds unnecessary JS parse cost to text-only posts, so it helps to define clear boundaries upfront.
| Criterion | Static image (PNG/WebP) | Mermaid xychart-beta | Conditional Chart.js 4 (chart: true) |
|---|---|---|---|
| Extra JS payload | 0 KB (image bytes only) | 0 KB (bundled in Chirpy mermaid@11) | ~65 KB gzip (chart: true posts only) |
| Dark/light mode | Fixed unless you ship two assets | Updates with theme | Live sync via MutationObserver |
| Interactivity | None | Simple single-series bar/line | Multi-series, doughnut, scatter, hover tooltips |
| Edit workflow | Re-export and re-upload | Edit Markdown text directly | Edit JSON text directly |
| Best fit | Real Grafana or DevTools captures | Quick single-series before/after bars | Grouped bars, multi-metric benchmarks |
For a simple two-to-four-item comparison, a Markdown table or built-in xychart-beta is plenty. And never redraw real monitoring proof—like Grafana panels or Lighthouse reports—as synthetic charts; actual screenshots carry far more credibility. Reach for conditional Chart.js only when you need multiple datasets, hover tooltips, or specialized chart types.
Using Chirpy’s built-in Mermaid xychart-beta
Chirpy v7.6 automatically loads mermaid@11 from jsDelivr whenever a post sets mermaid: true in Front Matter. Because Mermaid 11 ships with xychart-beta, you can render clean bar and line charts with zero extra scripts or plugins.
Here is a live xychart-beta bar chart rendered directly from Markdown:
xychart-beta
title "p99 Latency by Garbage Collector (ms)"
x-axis ["ParallelGC", "G1GC", "Generational ZGC"]
y-axis "Latency (ms)" 0 --> 200
bar [185, 62, 4]
You get immediate visual contrast with zero additional network requests. Once you need multi-dataset legends, hover tooltips, or doughnut/radar charts, though, xychart-beta hits its limits—that’s where conditional Chart.js takes over.
Building a conditional Chart.js 4 loader and Kramdown IAL renderer
Just like in my post on placing manual AdSense units in Jekyll Chirpy, I avoided overriding _layouts/post.html or _includes/head.html so future Chirpy upgrades stay conflict-free. Instead, _includes/metadata-hook.html loads Chart.js 4 and my renderer only on posts that declare chart: true.
flowchart TD
FM["Front Matter (chart: true)"] --> HOOK["_includes/metadata-hook.html"]
HOOK -->|"Conditional defer load"| LIB["Chart.js 4 + chart-renderer.js"]
MD["json fence + {: .chart-js }"] --> DOM["Rouge div.chart-js"]
LIB -->|"JSON.parse and replace"| CANVAS["Responsive canvas + theme sync"]
DOM --> CANVAS
1. Conditional script injection in _includes/metadata-hook.html
1
2
3
4
5
<!-- _includes/metadata-hook.html -->
{% if page.chart %}
<script defer src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script defer src="{{ '/assets/js/chart-renderer.js' | relative_url }}"></script>
{% endif %}
Posts without chart: true don’t even emit those <script> tags, keeping regular articles at zero extra JavaScript cost.
2. Why I chose Kramdown IAL ({: .chart-js })
Embedding raw <canvas> and <script> blocks directly in Markdown clutters the source file and forces you to copy dark mode boilerplate into every post. Instead, I write a standard fenced json code block followed immediately by Kramdown’s Inline Attribute List (IAL): {: .chart-js }.
Under the hood, Kramdown and Rouge render that block as <div class="language-json highlighter-rouge chart-js">. Because Rouge uses its standard json lexer, you get zero unknown-language warnings—and RSS readers or GitHub’s Markdown viewer gracefully fall back to readable JSON instead of a blank box.
3. Dark mode-aware renderer (assets/js/chart-renderer.js)
After DOM load, the renderer reads each .chart-js block with JSON.parse() and swaps it for a styled card containing a <canvas>. When a reader toggles Chirpy v7.6’s theme switch, Chirpy updates data-bs-theme on document.documentElement and posts a theme-updated message. Hooking up a MutationObserver alongside message and prefers-color-scheme listeners lets me re-theme axes, grids, legends, and radial scales via chart.update('none') with zero flicker.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// assets/js/chart-renderer.js (core excerpt)
function isDarkMode() {
var attr =
document.documentElement.getAttribute('data-bs-theme') ||
document.documentElement.getAttribute('data-mode');
if (attr === 'dark') return true;
if (attr === 'light') return false;
if (window.Theme && typeof window.Theme.isDark === 'boolean') {
return window.Theme.isDark;
}
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}
function renderCharts() {
if (typeof window.Chart === 'undefined') return;
document.querySelectorAll('.chart-js').forEach(function (block) {
// When Rouge line_numbers: true is enabled, skip td.rouge-gutter and read only code
var codeEl =
block.querySelector('td.rouge-code pre') ||
block.querySelector('pre code') ||
block.querySelector('code');
if (!codeEl) return;
var config = JSON.parse(codeEl.textContent);
var container = document.createElement('div');
container.className = 'chart-container';
var canvas = document.createElement('canvas');
container.appendChild(canvas);
block.parentNode.replaceChild(container, block);
var chart = new window.Chart(canvas.getContext('2d'), applyTheme(config));
instances.push(chart);
});
}
4. Responsive card styling with Chirpy CSS tokens
When maintainAspectRatio: false is set in Chart.js, the parent container needs an explicit height to prevent layout shifts. At the bottom of assets/css/jekyll-theme-chirpy.scss—right below the rules from my Chirpy mobile typography and Rouge error fix—I reused Chirpy’s built-in variables (--card-bg, --card-shadow, --card-header-bg, --tb-border-color) and split chart body heights between desktop (320px) and mobile (260px).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// assets/css/jekyll-theme-chirpy.scss
.chart-card {
margin: 1.75rem 0;
border-radius: 0.625rem;
background-color: var(--card-bg);
box-shadow: var(--card-shadow);
overflow: hidden;
}
.chart-card-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 1.15rem;
border-bottom: 1px solid var(--tb-border-color);
background-color: var(--card-header-bg, var(--highlight-bg-color));
}
.chart-card-body {
position: relative;
width: 100%;
height: 320px;
padding: 1.15rem 1.25rem 0.9rem;
}
@media (max-width: 767.98px) {
.chart-card-body {
height: 260px;
padding: 0.9rem 0.75rem 0.65rem;
}
}
Live Chart.js gallery with JSON source toggle
Because this post declares chart: true, all eight charts below render live from plain JSON code blocks tagged with {: .chart-js }—covering grouped bars, doughnut, multi-point XY scatter, filled area line, horizontal stacked bars, 3D bubble, radar, and polar area. Click the JSON toggle button in the top-right corner of any card to inspect its raw config, or toggle the sidebar theme switch to watch the palette and axes update in real time.
1. Grouped bar chart (bar)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
"type": "bar",
"data": {
"labels": ["HTTP/1.1", "HTTP/2", "HTTP/3 (QUIC)"],
"datasets": [
{
"label": "Clean network initial load (ms)",
"data": [780, 440, 390]
},
{
"label": "2% packet loss initial load (ms)",
"data": [1620, 1480, 520]
}
]
},
"options": {
"plugins": {
"title": {
"display": true,
"text": "Initial page load time by HTTP protocol and packet loss"
}
},
"scales": {
"y": {
"beginAtZero": true,
"title": {
"display": true,
"text": "ms"
}
}
}
}
}
2. Doughnut chart (doughnut)
Doughnut charts work well for proportional breakdowns like JVM memory footprint or traffic shares. The renderer defaults to cutout: '64%' and draws slice borders using --card-bg so segments stay distinct in dark mode.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
"type": "doughnut",
"data": {
"labels": [
"Heap (512MB)",
"Metaspace (120MB)",
"GC / Native (85MB)",
"CodeCache (80MB)",
"Thread Stack (75MB)",
"Direct Buffer (64MB)"
],
"datasets": [
{
"label": "Memory usage (MB)",
"data": [512, 120, 85, 80, 75, 64]
}
]
},
"options": {
"plugins": {
"title": {
"display": true,
"text": "Spring Boot JVM RSS memory breakdown in a 1GB container (MB)"
}
}
}
}
3. Multi-point XY scatter chart (scatter)
For latency distributions under increasing concurrency or outlier inspection, scatter takes { "x": ..., "y": ... } coordinate arrays. My renderer enables both X/Y gridlines and nearest hover mode so dense clusters remain easy to inspect.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
{
"type": "scatter",
"data": {
"datasets": [
{
"label": "Tomcat thread pool (max=200)",
"data": [
{ "x": 20, "y": 42 }, { "x": 40, "y": 48 }, { "x": 60, "y": 55 },
{ "x": 80, "y": 64 }, { "x": 100, "y": 78 }, { "x": 120, "y": 95 },
{ "x": 140, "y": 118 }, { "x": 160, "y": 152 }, { "x": 180, "y": 210 },
{ "x": 200, "y": 315 }, { "x": 220, "y": 490 }, { "x": 240, "y": 710 },
{ "x": 260, "y": 960 }, { "x": 280, "y": 1240 }, { "x": 300, "y": 1580 },
{ "x": 320, "y": 1920 }, { "x": 340, "y": 2280 }, { "x": 360, "y": 2650 }
]
},
{
"label": "Java 21 Virtual Threads",
"data": [
{ "x": 20, "y": 41 }, { "x": 40, "y": 45 }, { "x": 60, "y": 49 },
{ "x": 80, "y": 53 }, { "x": 100, "y": 58 }, { "x": 120, "y": 64 },
{ "x": 140, "y": 70 }, { "x": 160, "y": 77 }, { "x": 180, "y": 84 },
{ "x": 200, "y": 92 }, { "x": 220, "y": 101 }, { "x": 240, "y": 112 },
{ "x": 260, "y": 124 }, { "x": 280, "y": 139 }, { "x": 300, "y": 156 },
{ "x": 320, "y": 175 }, { "x": 340, "y": 198 }, { "x": 360, "y": 224 }
]
}
]
},
"options": {
"plugins": {
"title": {
"display": true,
"text": "External I/O API latency vs. concurrent virtual users (VU)"
}
},
"scales": {
"x": {
"type": "linear",
"title": {
"display": true,
"text": "Concurrent requests (VU)"
}
},
"y": {
"beginAtZero": true,
"title": {
"display": true,
"text": "p95 response time (ms)"
}
}
}
}
}
4. Filled area line chart (line + fill: true)
For time-series p99 trends or GC pause spikes, setting "fill": true makes gaps between series stand out immediately. The renderer applies tension: 0.34 and a translucent fill (alpha: 0.16) automatically.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{
"type": "line",
"data": {
"labels": ["00m", "05m", "10m", "15m", "20m", "25m", "30m", "35m", "40m", "45m"],
"datasets": [
{
"label": "G1GC p99 (ms)",
"data": [28, 34, 82, 41, 37, 118, 45, 39, 96, 36],
"fill": true
},
{
"label": "Generational ZGC p99 (ms)",
"data": [9, 10, 11, 10, 12, 11, 10, 9, 11, 10],
"fill": true
}
]
},
"options": {
"plugins": {
"title": {
"display": true,
"text": "p99 latency over a 45-minute load test by GC algorithm"
}
},
"scales": {
"y": {
"beginAtZero": true,
"title": {
"display": true,
"text": "p99 Latency (ms)"
}
}
}
}
}
5. Horizontal stacked bar chart (bar + indexAxis: "y" + stacked: true)
When you want to show both total size and layer breakdown—such as Docker image layers or request latency segments—horizontal stacked bars read cleanly even on narrow screens.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
{
"type": "bar",
"data": {
"labels": [
"Single-stage JDK",
"Multi-stage JRE",
"Distroless + jlink"
],
"datasets": [
{ "label": "OS base", "data": [118, 78, 22] },
{ "label": "JVM runtime", "data": [340, 145, 48] },
{ "label": "Dependency JARs", "data": [64, 64, 64] },
{ "label": "Application", "data": [8, 8, 8] }
]
},
"options": {
"indexAxis": "y",
"plugins": {
"title": {
"display": true,
"text": "Spring Boot Docker image layer size by build strategy (MB)"
}
},
"scales": {
"x": {
"stacked": true,
"title": {
"display": true,
"text": "Image size (MB)"
}
},
"y": {
"stacked": true
}
}
}
}
6. Three-dimensional bubble chart (bubble)
Combining x (requests per second), y (p95 latency), and r (error impact radius) packs three metrics into one chart. Large bubbles in the upper-right quadrant highlight the highest-priority optimization targets at a glance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
{
"type": "bubble",
"data": {
"datasets": [
{
"label": "Read APIs (GET)",
"data": [
{ "x": 420, "y": 35, "r": 7 },
{ "x": 680, "y": 58, "r": 10 },
{ "x": 910, "y": 145, "r": 16 },
{ "x": 260, "y": 24, "r": 6 },
{ "x": 540, "y": 82, "r": 9 }
]
},
{
"label": "Write & payment APIs (POST)",
"data": [
{ "x": 110, "y": 180, "r": 12 },
{ "x": 195, "y": 340, "r": 18 },
{ "x": 310, "y": 520, "r": 22 },
{ "x": 85, "y": 130, "r": 8 },
{ "x": 240, "y": 410, "r": 15 }
]
},
{
"label": "External integration APIs",
"data": [
{ "x": 65, "y": 620, "r": 14 },
{ "x": 140, "y": 790, "r": 20 }
]
}
]
},
"options": {
"plugins": {
"title": {
"display": true,
"text": "API endpoints by RPS, p95 latency, and outage impact (radius)"
}
},
"scales": {
"x": {
"beginAtZero": true,
"title": {
"display": true,
"text": "Requests per second (RPS)"
}
},
"y": {
"beginAtZero": true,
"title": {
"display": true,
"text": "p95 latency (ms)"
}
}
}
}
}
7. Multi-axis radar chart (radar)
Radar charts help compare concurrency models or architecture options across five to six dimensions. The renderer sets backdropColor: 'transparent' on radial scale ticks (scales.r) so tick numbers never show white boxes in dark mode.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{
"type": "radar",
"data": {
"labels": [
"I/O throughput",
"Debugging ease",
"Memory efficiency",
"JDBC & JPA compatibility",
"Learning curve",
"Massive streaming"
],
"datasets": [
{
"label": "Spring MVC (Platform Threads)",
"data": [55, 95, 55, 100, 95, 45]
},
{
"label": "Spring MVC + Virtual Threads",
"data": [85, 90, 82, 92, 90, 68]
},
{
"label": "Spring WebFlux (Netty)",
"data": [96, 52, 95, 40, 48, 98]
}
]
},
"options": {
"plugins": {
"title": {
"display": true,
"text": "Spring server concurrency model trade-offs (out of 100)"
}
},
"scales": {
"r": {
"min": 0,
"max": 100,
"ticks": {
"stepSize": 25
}
}
}
}
}
8. Polar area chart (polarArea)
Polar area charts emphasize absolute magnitude differences via sector radius. Here is the top-level category distribution of published posts across this blog:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
"type": "polarArea",
"data": {
"labels": [
"Spring",
"Vite",
"Java",
"Home Server",
"Docker",
"Blog",
"CS",
"Book & AI & Dev"
],
"datasets": [
{
"label": "Published posts",
"data": [53, 31, 23, 17, 16, 14, 10, 24]
}
]
},
"options": {
"plugins": {
"title": {
"display": true,
"text": "Namju's Commit Log published post distribution by category (188 total)"
}
}
}
}
Because a JSON syntax typo or a missing chart: true flag doesn’t fail jekyll build, broken charts can silently ship as raw code blocks. I extended qa_check.py to run json.loads() on every {: .chart-js } block and verify that chart: true in Front Matter matches the presence of chart blocks in the post body.
Production caveats and deployment checklist
Warning: If
_config.ymlenables Rougeline_numbers: true, readingcode.textContentdirectly pulls gutter line numbers (td.rouge-gutter) into the string and breaksJSON.parse(). Always querytd.rouge-code prefirst. Also remember that JSON configs can’t hold JavaScript callbacks (ticks.callback: function() {}), so stick to declarative Chart.js options.
Load Chart.js and chart-renderer.js with defer so they never block initial article rendering, and keep container heights fixed in CSS so chart hydration causes zero Cumulative Layout Shift (CLS).
Before rolling this setup out on your own Chirpy site, check these four items:
- Use built-in Mermaid
xychart-betafor simple single-series comparisons; reservechart: truefor multi-series or interactive charts. - Verify
_includes/metadata-hook.htmlgates Chart.js behindpage.chartso regular posts stay at 0 extra bytes. - Test both desktop and
390pxmobile viewports while toggling light/dark themes to confirm axis and legend legibility. - Run
qa_check.pybefore deploying to confirmchart: truealignment and zero JSON parse errors.