loading...

WordPress Fallback CSS

peiche profile image Paul ・2 min read

I'm writing a WordPress theme. In it, I make liberal use of custom properties. I don't want to completely leave IE users in the cold, so as part of my build process I'm using a modified postcss-css-variables to generate fallback values.

I initially baked all this into the stylesheet, but that proved excessive. Plus, I don't want to penalize users of modern browsers. So now I'm building two stylesheets as part of the build process: one which uses custom properties, and one which contains static, fallback values. The question now is how best to load the best one for each user.

I rather like the approach that the folks at CodyHouse use for their framework:

<script>
  if('CSS' in window && CSS.supports('color', 'var(--color-var)')) {
    document.write('<link rel="stylesheet" href="assets/css/style.css">');
  } else {
    document.write('<link rel="stylesheet" href="assets/css/style-fallback.css">');
  }
</script>
<noscript>
  <link rel="stylesheet" href="assets/css/style-fallback.css">
</noscript>

Unfortunately, it's not possible using WordPress's wp_enqueue_style method to load a stylesheet inside a noscript tag. The approach I'm taking right now is the reverse of the above: I'm loading the modern stylesheet by default, then running some js to detect browsers that aren't supported:

if ( ! ( 'CSS' in window && CSS.supports('color', 'var(--color-var)') ) ) {
    const css = document.getElementById( 'screen-css' );
    css.href = css.href.replace( 'screen', 'screen-fallback' );
}

This will replace the stylesheet with the fallback if custom properties are not supported. This results in no change of experience for modern browsers (aside from a little snippet of js), while IE users will get a brief FOUT while the stylesheets are swapped.

So given the limitations of how WordPress loads stylesheets, can this be improved?

Discussion

pic
Editor guide
Collapse
vanaf1979 profile image
VA79 Stephan

You probably found an answer by now, but let me add some options for you.

Maybe you can achieve the desired effect with html conditionals!? I wrote a article about these and other enqueue options here: vanaf1979.nl/wordpress-css-styles-... (Scroll down to "Adding Conditional stylesheets:")

As for your first option... You're right that you can't enqueue noscripts, but adding these to the head is actually pretty simple. I have created a little Gist for you with a implementation of your noscript here: gist.github.com/vanaf1979/b6f5d57d...

Or maybe you can just restructure your Css and implement some progressive enhancements using @support. Check out this article: dev.to/lampewebdev/css-quickies-su...

Hope this helps...

I'm curious what your final solution is, so please share. ;)

Thanks