Skip to content

Instantly share code, notes, and snippets.

@apeschar
Created May 25, 2021 07:05
Show Gist options
  • Save apeschar/bf3a2ab38a04586c264294edd3e983a8 to your computer and use it in GitHub Desktop.
Save apeschar/bf3a2ab38a04586c264294edd3e983a8 to your computer and use it in GitHub Desktop.
Attempt to fix Twenty Twenty One dark theme flash when using PhastPress
<?php
// Either save this entire file as dark-theme-fix.php and put it inside
// wp-content/mu-plugins (you may have to create this directory),
// or manually add the script tag to your HTML <HEAD>.
add_action('wp_head', function () { ?>
<script data-phast-no-defer>
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
document.documentElement.classList.add("is-dark-theme");
new MutationObserver(function (mutations, observer) {
if (document.body) {
document.body.classList.add("is-dark-theme");
observer.disconnect();
}
})
.observe(document.documentElement, {childList: true});
}
</script>
<?php });
@umhan35
Copy link

umhan35 commented May 25, 2021

Thanks, Albert. But the code didn't work... But I figured it out -- I just added some JS right after the openning <body> tag.

Below is the code that works:

<?php
add_action('wp_body_open', function () { ?> <!-- 2021 theme supports this action here:
https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwentyone/header.php#L24 -->

<script data-phast-no-defer> // just used the theme JS code here: https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwentyone/assets/js/dark-mode-toggler.js
	function toggleDarkModeEarly () {
		var isDarkMode = window.matchMedia( '(prefers-color-scheme: dark)' ).matches;

		if ( 'yes' === window.localStorage.getItem( 'twentytwentyoneDarkMode' ) ) {
			isDarkMode = true;
		} else if ( 'no' === window.localStorage.getItem( 'twentytwentyoneDarkMode' ) ) {
			isDarkMode = false;
		}

		if ( isDarkMode ) {
			document.documentElement.classList.add( 'is-dark-theme' );
			document.body.classList.add( 'is-dark-theme' );
		} else {
			document.documentElement.classList.remove( 'is-dark-theme' );
			document.body.classList.remove( 'is-dark-theme' );
		}
	}
	toggleDarkModeEarly();
</script>

<?php });

@apeschar
Copy link
Author

Thanks @umhan35 for your assistance!

In case anyone sees this: the problem should be fixed in PhastPress 1.123. You should no longer need the code in this gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment