mirror of
https://github.com/cotes2020/jekyll-theme-chirpy.git
synced 2026-06-21 23:38:39 +00:00
ceb2a41463
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.
65 lines
2.2 KiB
HTML
65 lines
2.2 KiB
HTML
<!-- https://giscus.app/ -->
|
|
<script>
|
|
(function () {
|
|
const themeMapper = Theme.getThemeMapper('light', 'dark_dimmed');
|
|
const initTheme = themeMapper[Theme.visualState];
|
|
|
|
let lang = '{{ site.comments.giscus.lang | default: lang }}';
|
|
{%- comment -%} https://github.com/giscus/giscus/tree/main/locales {%- endcomment -%}
|
|
if (lang.length > 2 && !lang.startsWith('zh')) {
|
|
lang = lang.slice(0, 2);
|
|
}
|
|
|
|
let giscusAttributes = {
|
|
src: 'https://giscus.app/client.js',
|
|
'data-repo': '{{ site.comments.giscus.repo}}',
|
|
'data-repo-id': '{{ site.comments.giscus.repo_id }}',
|
|
'data-category': '{{ site.comments.giscus.category }}',
|
|
'data-category-id': '{{ site.comments.giscus.category_id }}',
|
|
'data-mapping': '{{ site.comments.giscus.mapping | default: 'pathname' }}',
|
|
'data-strict' : '{{ site.comments.giscus.strict | default: '0' }}',
|
|
'data-reactions-enabled': '{{ site.comments.giscus.reactions_enabled | default: '1' }}',
|
|
'data-emit-metadata': '0',
|
|
'data-theme': initTheme,
|
|
'data-input-position': '{{ site.comments.giscus.input_position | default: 'bottom' }}',
|
|
'data-lang': lang,
|
|
'data-loading': 'lazy',
|
|
crossorigin: 'anonymous',
|
|
async: ''
|
|
};
|
|
|
|
let giscusNode = document.createElement('script');
|
|
Object.entries(giscusAttributes).forEach(([key, value]) =>
|
|
giscusNode.setAttribute(key, value)
|
|
);
|
|
|
|
const $footer = document.querySelector('footer');
|
|
$footer.insertAdjacentElement("beforebegin", giscusNode);
|
|
|
|
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 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');
|
|
}
|
|
});
|
|
})();
|
|
</script>
|