Fix: Check if theme button elements exist before adding event listeners

The mermaid-init script was throwing 'Uncaught TypeError: can't access
property addEventListener, document.getElementById(...) is null' because
it tried to attach click handlers to theme toggle buttons (ayu, navy, coal,
light, rust) that may not exist on all pages.

Fixed by:
- Wrapping theme button event listener registration in null checks
- Using DOMContentLoaded fallback when document is still loading
- Keeping mermaid.initialize() call outside the check since it needs to
  run early with startOnLoad: true
This commit is contained in:
2026-03-19 20:14:58 -07:00
parent 917b550916
commit faa30b9285

View File

@@ -21,19 +21,33 @@
// Simplest way to make mermaid re-render the diagrams in the new theme is via refreshing the page
for (const darkTheme of darkThemes) {
document.getElementById(darkTheme).addEventListener('click', () => {
if (lastThemeWasLight) {
window.location.reload();
function initThemeButtons() {
for (const darkTheme of darkThemes) {
const darkBtn = document.getElementById(darkTheme);
if (darkBtn) {
darkBtn.addEventListener('click', () => {
if (lastThemeWasLight) {
window.location.reload();
}
});
}
});
}
for (const lightTheme of lightThemes) {
const lightBtn = document.getElementById(lightTheme);
if (lightBtn) {
lightBtn.addEventListener('click', () => {
if (!lastThemeWasLight) {
window.location.reload();
}
});
}
}
}
for (const lightTheme of lightThemes) {
document.getElementById(lightTheme).addEventListener('click', () => {
if (!lastThemeWasLight) {
window.location.reload();
}
});
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initThemeButtons);
} else {
initThemeButtons();
}
})();