From ceb2a41463cbb6251fa257b640990a8d9717b0bb Mon Sep 17 00:00:00 2001 From: Cotes Chung <11371340+cotes2020@users.noreply.github.com> Date: Sat, 23 May 2026 23:00:48 +0800 Subject: [PATCH] fix(giscus): synchronize theme state during lazy loading (#2742) Previously, theme switch events were lost if triggered before the Giscus iframe was fully loaded (e.g., when deferred by lazy loading or before the client script executed). This resulted in Giscus rendering with the outdated initial theme once it finally appeared in the viewport. This commit handles these edge cases by: 1. Updating the `data-theme` attribute on the Giscus script node if the iframe hasn't been created yet. 2. Modifying the `theme` query parameter in the iframe's `src` URL if it is currently in a pending/lazy-loading state. --- _includes/comments/giscus.html | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/_includes/comments/giscus.html b/_includes/comments/giscus.html index 805847202..2d5f7e7bf 100644 --- a/_includes/comments/giscus.html +++ b/_includes/comments/giscus.html @@ -39,16 +39,25 @@ addEventListener('message', (event) => { if (event.source === window && event.data && event.data.id === Theme.ID) { const newTheme = themeMapper[Theme.visualState]; - const message = { setConfig: { theme: newTheme } }; - const giscus = - document.getElementsByClassName('giscus-frame')[0].contentWindow; - giscus.postMessage({ giscus: message }, 'https://giscus.app'); + const iframe = document.querySelector('.giscus-frame'); + + if (!iframe) { + return; + } + + if (iframe.classList.contains('giscus-frame--loading')) { + let url = new URL(iframe.src); + url.searchParams.set('theme', newTheme); + iframe.src = url.toString(); + } + + iframe.contentWindow.postMessage({ giscus: message }, 'https://giscus.app'); } }); })();