Fix the white/black theme switch in Chrome
Chrome doesn't fire twice the load event on a stylesheet when the disabled attribute is toggled (enabled => disabled => enabled)
This commit is contained in:
parent
be8e44e17e
commit
f574247452
1 changed files with 39 additions and 17 deletions
44
src/theme.ts
44
src/theme.ts
|
@ -279,26 +279,48 @@ export async function setTheme(theme?: string): Promise<void> {
|
||||||
resolve();
|
resolve();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const isStyleSheetLoaded = () => Boolean(
|
||||||
|
[...document.styleSheets]
|
||||||
|
.find(styleSheet => styleSheet?.href === styleElements[stylesheetName].href),
|
||||||
|
);
|
||||||
|
|
||||||
|
function waitForStyleSheetLoading() {
|
||||||
// turns out that Firefox preloads the CSS for link elements with
|
// turns out that Firefox preloads the CSS for link elements with
|
||||||
// the disabled attribute, but Chrome doesn't.
|
// the disabled attribute, but Chrome doesn't.
|
||||||
|
if (isStyleSheetLoaded()) {
|
||||||
|
switchTheme();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
let cssLoaded = false;
|
let counter = 0;
|
||||||
|
|
||||||
|
// In case of theme toggling (white => black => white)
|
||||||
|
// Chrome doesn't fire the `load` event when the white theme is selected the second times
|
||||||
|
const intervalId = setInterval(() => {
|
||||||
|
if (isStyleSheetLoaded()) {
|
||||||
|
clearInterval(intervalId);
|
||||||
|
styleElements[stylesheetName].onload = undefined;
|
||||||
|
styleElements[stylesheetName].onerror = undefined;
|
||||||
|
switchTheme();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Avoid to be stuck in an endless loop if there is an issue in the stylesheet loading
|
||||||
|
counter++;
|
||||||
|
if (counter === 5) {
|
||||||
|
clearInterval(intervalId);
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
|
||||||
styleElements[stylesheetName].onload = () => {
|
styleElements[stylesheetName].onload = () => {
|
||||||
|
clearInterval(intervalId);
|
||||||
switchTheme();
|
switchTheme();
|
||||||
};
|
};
|
||||||
|
|
||||||
for (let i = 0; i < document.styleSheets.length; i++) {
|
styleElements[stylesheetName].onerror = () => {
|
||||||
const ss = document.styleSheets[i];
|
clearInterval(intervalId);
|
||||||
if (ss && ss.href === styleElements[stylesheetName].href) {
|
};
|
||||||
cssLoaded = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cssLoaded) {
|
waitForStyleSheetLoading();
|
||||||
styleElements[stylesheetName].onload = undefined;
|
|
||||||
switchTheme();
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue