Skip to content

Commit ee35ed3

Browse files
authored
Rollup merge of #93253 - jsha:theme-on-show, r=GuillaumeGomez
Update theme on pageshow event When a user goes forward or back, the page may be rendered from the back/forward cache (https://web.dev/bfcache/) rather than from scratch. If they have changed theme in the meantime, that means seeing an incorrect theme on the page they went forward or back to. The `pageshow` event fires on such navigations, so we can update the theme based on that event. Demo: https://rustdoc.crud.net/jsha/theme-on-show/std/string/trait.ToString.html r? `@GuillaumeGomez`
2 parents d1aa2f7 + b30725e commit ee35ed3

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

Diff for: src/librustdoc/html/static/js/storage.js

+25-6
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,15 @@ var updateSystemTheme = (function() {
216216
};
217217
})();
218218

219+
function switchToSavedTheme() {
220+
switchTheme(
221+
window.currentTheme,
222+
window.mainTheme,
223+
getSettingValue("theme") || "light",
224+
false
225+
);
226+
}
227+
219228
if (getSettingValue("use-system-theme") !== "false" && window.matchMedia) {
220229
// update the preferred dark theme if the user is already using a dark theme
221230
// See https://github.com/rust-lang/rust/pull/77809#issuecomment-707875732
@@ -228,10 +237,20 @@ if (getSettingValue("use-system-theme") !== "false" && window.matchMedia) {
228237
// call the function to initialize the theme at least once!
229238
updateSystemTheme();
230239
} else {
231-
switchTheme(
232-
window.currentTheme,
233-
window.mainTheme,
234-
getSettingValue("theme") || "light",
235-
false
236-
);
240+
switchToSavedTheme();
237241
}
242+
243+
// If we navigate away (for example to a settings page), and then use the back or
244+
// forward button to get back to a page, the theme may have changed in the meantime.
245+
// But scripts may not be re-loaded in such a case due to the bfcache
246+
// (https://web.dev/bfcache/). The "pageshow" event triggers on such navigations.
247+
// Use that opportunity to update the theme.
248+
// We use a setTimeout with a 0 timeout here to put the change on the event queue.
249+
// For some reason, if we try to change the theme while the `pageshow` event is
250+
// running, it sometimes fails to take effect. The problem manifests on Chrome,
251+
// specifically when talking to a remote website with no caching.
252+
window.addEventListener("pageshow", function(ev) {
253+
if (ev.persisted) {
254+
setTimeout(switchToSavedTheme, 0);
255+
}
256+
});

0 commit comments

Comments
 (0)