Describe the bug
Automatic system theme setting does not take effect until after two page refreshes. This is caused by PHP, as the server-side code base, not able to instantly fetch client-side values provided by the browser. The current implementation saves the system theme to local storage and PHP loads the value from there. Some possible solutions are:
- to use ajax
- load the system theme to local storage instantly after the option is selected
- listen for theme changes
- run the theme engine entirely on Javascript
Google.com also has the same issue with light and dark mode, requiring another refresh to load the correct theme, since they also use server-side rendering to display search results. Youtube.com solves this issue by forcing the browser to refresh after the first visit to the page.
To Reproduce
Steps to reproduce the behavior:
- Go to Appearance โ Material Dashboard
- Change theme setting to
System
- Save changes
- No changes to page theme
- Refresh the page, changes are applied
Expected behavior
The system theme option should apply instantly after saving changes.
Additional context
The methods to get current system theme are as follows:
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
// dark mode
}
Or to watch for system theme changes:
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
const newColorScheme = event.matches ? "dark" : "light";
});